Skip to content

Instantly share code, notes, and snippets.

@joynal
Created November 21, 2021 12:45
Show Gist options
  • Save joynal/3804098215937c02671a1984c66fef0b to your computer and use it in GitHub Desktop.
Save joynal/3804098215937c02671a1984c66fef0b to your computer and use it in GitHub Desktop.
/*
* Given two functions `head` and `tail`
* Implement the array `map` function using this two fucntions.
* Example: `map([1,2,3], (n) => n * 2) == [2,4,6]`
*/
const head = (array) => array[0];
const tail = (array) => array.slice(1, array.length);
/* Example: map([1,2,3], (n) => n * 2) === [2,4,6]
*/
const map = (array, fun) => {
// implement this function
if (array.length === 0) return [];
return [fun(head(array))].concat(map(tail(array), fun));
};
console.log(map([1, 2, 3], (n) => n * 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment