Skip to content

Instantly share code, notes, and snippets.

@qsona
Last active August 30, 2016 16:52
Show Gist options
  • Save qsona/ff816c30b0a0c9782103314a8c356c3d to your computer and use it in GitHub Desktop.
Save qsona/ff816c30b0a0c9782103314a8c356c3d to your computer and use it in GitHub Desktop.
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 ]
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 ]
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