Skip to content

Instantly share code, notes, and snippets.

@ashwinkumar2438
Created September 9, 2020 18:32
Show Gist options
  • Save ashwinkumar2438/ac32ee1807f1e78e5720d66cbc07fe63 to your computer and use it in GitHub Desktop.
Save ashwinkumar2438/ac32ee1807f1e78e5720d66cbc07fe63 to your computer and use it in GitHub Desktop.
//map function.
var map=(array,operator)=>{
let maparr=[];
for(let i=0;i<array.length;i++){
maparr.push(operator(array[i],i,array))
}
return maparr;
}
map([1,2,3],(a)=>a*2); //(3) [2, 4, 6]
//reduce function.
var reduce=(...args)=>{
let [array,operator,initialval]=args;
let accumulator=args.length===3?initialval:array[0];
for(let i=3-args.length;i<array.length;i++){
accumulator=operator(accumulator,array[i],i,array);
}
return accumulator;
}
reduce([1,2,3],(acc,i)=>acc+i); //6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment