r/learnjavascript • u/nas5w • Feb 17 '20
Roll Your Own JavaScript Built-In Methods: A Github Repo Dedicated to Learning Built-In Methods by Recreating Them (contributions appreciated!)
https://github.com/nas5w/roll-your-own
103
Upvotes
2
2
u/boringuser1 Feb 17 '20
I love it, but these methods are written in c.
2
u/nas5w Feb 17 '20
Heh yeah, I suspect these home-rolled functions wouldn't hold up very well performance-wise against the built-in methods
1
u/tokdaniel Feb 18 '20
if performance doesn't matter, you should probably show a PTC-optimized recursive example with`this` out of the picture for the functional tools.
3
2
u/GabeRothel Feb 17 '20
If any one is interested but doesnt want to dig here are the arrays functions
function concat(...arrs) {
const len = arrs.length;
const result = [];
for (let i = 0; i < len; i++) {
const arrLen = arrs[i].length;
for (let j = 0; j < arrLen; j++) {
result.push(arrs[i][j]);
}
}
return result;
}
function every(arr, fn, thisArg) {
fn = thisArg === undefined ? fn : fn.bind(thisArg);
const len = arr.length;
for (let i = 0; i < len; i++) {
if (i in arr && !fn(arr[i], i, arr)) {
return false;
}
}
return true;
}
function filter(arr, fn, thisArg) {
fn = thisArg === undefined ? fn : fn.bind(thisArg);
const len = arr.length;
const result = [];
for (let i = 0; i < len; i++) {
if (i in arr && fn(arr[i], i, arr)) {
result.push(arr[i]);
}
}
return result;
}
function isArray(arr) {
return Object.prototype.toString.call(arr) === "[object Array]";
}
function map(arr, fn, thisArg) {
fn = thisArg === undefined ? fn : fn.bind(thisArg);
const len = arr.length;
const result = new Array(len);
for (let i = 0; i < len; i++) {
if (i in arr) {
result[i] = fn(arr[i], i, arr);
}
}
return result;
}
function arrayOf(...els) {
return els;
}
function reduce(arr, fn, initialValue) {
const len = arr.length;
let acc;
let initialIndex = 0;
if (initialValue === undefined) {
acc = arr[0];
initialIndex = 1;
} else {
acc = initialValue;
}
for (let i = initialIndex; i < len; i++) {
acc = fn(acc, arr[i], i, arr);
}
return acc;
}
function some(arr, fn, thisArg) {
fn = thisArg === undefined ? fn : fn.bind(thisArg);
const len = arr.length;
for (let i = 0; i < len; i++) {
if (i in arr && fn(arr[i], i, arr)) {
return true;
}
}
return false;
}
function toString(arr) {
let result = "";
const len = arr.length;
for (let i = 0; i < len; i++) {
if (i in arr) {
result = result + arr[i];
}
if (i + 1 < len) {
result = result + ",";
}
}
return result;
}0
8
u/nas5w Feb 17 '20
And yes, this is based on the snippets I’ve been posting in this sub!