Created
October 13, 2019 08:57
-
-
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.
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
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