Skip to content

Instantly share code, notes, and snippets.

@ummahusla
Created November 21, 2022 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ummahusla/cc06f086c40d2030f4a7ed5a09d06a6e to your computer and use it in GitHub Desktop.
Save ummahusla/cc06f086c40d2030f4a7ed5a09d06a6e to your computer and use it in GitHub Desktop.
JavaScript DYI map, filter, reduce
const arr = [1, 2, 3, 4, 1, 2, 3];
const originalMap = arr.map(i => i + 1);
const myMap = (arr, cb) => {
let temp = [];
for(let i = 0; i < arr.length; i++) {
temp.push(cb(arr[i]));
}
return temp;
}
const myMapTest = myMap(arr, (i => i + 1));
const originalFilter = arr.filter(i => i === 1);
const myFilter = (arr, cb) => {
let temp = [];
for(let i = 0; i < arr.length; i++) {
if (cb(arr[i])) temp.push(arr[i]);
}
return temp;
}
const myFiltertest = myFilter(arr, (i => i === 1));
const originalReduce = arr.reduce((a, b) => a + b);
const myReduce = (arr, cb, init = arr[0]) => {
let temp = init;
for(let i = 0; i < arr.length; i++) {
temp = cb(temp, arr[i]);
}
return temp;
}
console.log(myReduce(arr, (a, b) => a * b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment