Last active
August 30, 2016 16:52
-
-
Save qsona/ff816c30b0a0c9782103314a8c356c3d to your computer and use it in GitHub Desktop.
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 createEach = (withIndex) => { | |
return withIndex ? | |
(arr, iterator) => arr.forEach((elem, index) => iterator(elem, index)) : | |
(arr, iterator) => arr.forEach((elem) => iterator(elem)); | |
}; | |
const createMap = (withIndex) => { | |
return withIndex ? | |
(arr, iterator) => arr.map((elem, index) => iterator(elem, index)) : | |
(arr, iterator) => arr.map((elem) => iterator(elem)); | |
}; | |
const each = createEach(false); | |
each.withIndex = createEach(true); | |
const map = createMap(false); | |
map.withIndex = createMap(true); | |
map(['10', '10', '10'], parseInt); // [ 10, 10, 10 ] | |
map.withIndex(['10', '10', '10'], parseInt); // [ 10, NaN, 2 ] |
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 create = (forArrFn, withIndex) => { | |
return withIndex ? | |
(arr, iterator) => (forArrFn(arr)((elem, i) => iterator(elem, i))) : | |
(arr, iterator) => (forArrFn(arr)((elem) => iterator(elem))); | |
}; | |
const forArrEachFn = arr => arr.forEach.bind(arr); | |
const each = create(forArrEachFn, false); | |
each.withIndex = create(forArrEachFn, true); | |
const forArrMapFn = arr => arr.map.bind(arr); | |
const map = create(forArrMapFn, false); | |
map.withIndex = create(forArrMapFn, true); | |
map(['10', '10', '10'], parseInt); // [ 10, 10, 10 ] | |
map.withIndex(['10', '10', '10'], parseInt); // [ 10, NaN, 2 ] |
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 arrayMethods = ['forEach', 'map', 'filter']; | |
const anExcellentModule = {}; | |
arrayMethods.forEach((name) => { | |
anExcellentModule[name] = (arr, iterator) => arr[name](elem => iterator(elem)); | |
anExcellentModule[name].withIndex = (arr, iterator) => arr[name]((elem, i) => iterator(elem, i)); | |
}); | |
anExcellentModule.map(['10', '10', '10'], parseInt); // [ 10, 10, 10 ] | |
anExcellentModule.map.withIndex(['10', '10', '10'], parseInt); // [ 10, NaN, 2 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment