Skip to content

Instantly share code, notes, and snippets.

@nicholaskajoh
Created October 13, 2019 08:57
Show Gist options
  • Save nicholaskajoh/3de651a34175cd770139cfc987c7c988 to your computer and use it in GitHub Desktop.
Save nicholaskajoh/3de651a34175cd770139cfc987c7c988 to your computer and use it in GitHub Desktop.
Implementation of JavaScript's Array map function without the use of a loop (for, while etc). Recursion is used instead.
Array.prototype.customMap = function(fn) {
if (typeof fn !== 'function') throw Error('Am I a joke to you?');
const arr = this;
const arrLen = arr.length;
const getNewArr = (index, newArr) => {
if (index < arrLen) {
const newItem = fn(arr[index], index, arr);
return getNewArr(index + 1, [...newArr, newItem]);
} else {
return newArr;
}
};
return getNewArr(0, []);
}
// test
const arr = [1, 2, 3, 5, 6];
const newArr = arr.customMap((item, i) => {
return item + i;
});
console.log({ newArr });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment