Created
February 3, 2020 14:16
-
-
Save mpj/955034c4e1f507bf8e540e4a3c77f653 to your computer and use it in GitHub Desktop.
code from episode
This file contains 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
const isMoreThan5 = number => number > 5 | |
const numbers = [ 2, 4, 8, 9 ] | |
const result = filter(isMoreThan5, numbers) | |
const addThree = number => number + 3 | |
const result = map(addThree, numbers) | |
result | |
function map(transform, array) { | |
const initialArray = [] | |
const mapReducer = (mappedArray, currentItem) => | |
mappedArray.concat(transform(currentItem)) | |
return reduce(mapReducer, initialArray, array) | |
} | |
function filter(predicate, array) { | |
const initialArray = [] | |
const filterReducer = (filteredArray, currentItem) => { | |
const shouldBeIncluded = predicate(currentItem) | |
if(shouldBeIncluded) { | |
return filteredArray.concat(currentItem) | |
} | |
return filteredArray | |
} | |
return reduce(filterReducer, initialArray, array) | |
} | |
function reduce(reducer, initialAccumulatorValue, array) { | |
let accumulatorValue = initialAccumulatorValue | |
for (let i = 0; i < array.length; i++) { | |
const current = array[i] | |
current | |
accumulatorValue | |
accumulatorValue = | |
reducer(accumulatorValue, current) | |
accumulatorValue | |
} | |
return accumulatorValue | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Slight rewrite to make it work with sparse (ie. arrays with holes eg.
[2, , 4, 8, 9]
) of course I don't recommend using sparse arrays but javascript arrays can have holes. I also added in the additional parameters to the callback functions the index and the array itself that are in the native array methods.otherwise for
numbers = [2, , 4, 8, 9]
you get mapped result of[5, nan, 7, 11, 12]
when you should get[5, , 7, 11, 12]
with the hole preservefor more info see the blog post An adventure in sparse arrays by Remy Sharp.