Reduce Implementation
1
2
3
4
5
6
7
8
9
10
11
12
Array.prototype.myReduce = (cbFn, initialValue) => {
let accumulator = initialValue;
for (let i = 0; i < this.length; i++) {
if (accumulator !== undefined) {
accumulator = cbFn.call(undefined, accumulator, this[i], i, this);
} else {
accumulator = this[i];
}
}
return accumulator;
}
Flatten Array Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
function myFlat(arr, depth = 1, output = []) {
if (depth <= 0) {
output.push(arr);
return output;
} else {
for (const item of arr) {
if (Array.isArray(item)) {
myFlat(item, depth - 1, output);
} else output.push(item);
}
}
return output;
}
Array.bind() Implementation
1
2
3
4
5
6
7
Function.prototype.myBind = function(...args {
let callback = this, ctx = args.splice(1);
return function(...newArgs){
callback.call(args[0], ...[...ctx, ...newArgs]);
}
}
Debounce Implementation
1
2
3
4
5
6
7
8
9
10
11
const debounce = (func, delay) => {
let id;
return (...args)=>{
if(id) {
clearTimeout(id);
}
id = setTimeout(()=>{
func(...args);
}, delay)
}
}