Created
October 21, 2020 23:36
-
-
Save AkshatJen/573ea6aa2ef2b9b8098ef791fbd213fe to your computer and use it in GitHub Desktop.
Own version of map, reduce and filter (ES6)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// map | |
const map = (arr, func) => { | |
const outputArr = []; | |
for (let i = 0; i<arr.length; i++ ){ | |
outputArr.push(func(arr[i])); | |
} | |
return outputArr; | |
} | |
const multiply2 = num => num*2; | |
const multiply3 = num => num*3; | |
const square = num => num*num; | |
const answer1 = map([1,2,3],multiply2); | |
const answer2 = map([1,2,3],multiply3); | |
const answer3 = map([1,2,3],square); | |
console.log(answer1,answer2, answer3); | |
// reduce function | |
const reducer = (arr, callB, initial) => { | |
for (let i = 0; i<arr.length; i++ ){ | |
initial = callB(arr[i], initial); | |
} | |
return initial; | |
} | |
const add = (val,val2) => val+val2; | |
const answer = reducer([2,3,4], add,0); | |
console.log(answer); | |
// filter | |
const filter = (arr , condition) => { | |
const newArr = []; | |
for(let i = 0; i < arr.length; i ++){ | |
if(condition(arr[i])) newArr.push(arr[i]); | |
} | |
return newArr; | |
} | |
const isEven = num => (num%2 === 0) ? true : false; | |
const isOdd = num => (isEven(num)) ? false : true; | |
console.log(filter([0,2,4,6,8,9],isEven)); | |
console.log(filter([0,2,4,6,8,9],isOdd)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment