Skip to content

Instantly share code, notes, and snippets.

@coproduto
Created March 19, 2022 23:24
Show Gist options
  • Save coproduto/3a0d345b315e270adf144e4edb59a497 to your computer and use it in GitHub Desktop.
Save coproduto/3a0d345b315e270adf144e4edb59a497 to your computer and use it in GitHub Desktop.
const reverse = (array) =>
array.reduce((acc, elem) => [elem].concat(acc), []);
const map = (array, fun) =>
reverse(array.reduce((acc, elem) => [fun(elem)].concat(acc), []));
const filter = (array, pred) =>
reverse(array.reduce((acc, elem) => pred(elem) ? [elem].concat(acc) : acc, []));
@forsureitsme
Copy link

The array reversing in map and filter could be skipped by concatenating with the spread syntax.

const map = (array, fun) =>
  array.reduce((acc, elem) => [...acc, fun(elem)], []);
  
const filter = (array, pred) =>
  array.reduce((acc, elem) => pred(elem) ? [...acc, elem] : acc, []);

@coproduto
Copy link
Author

coproduto commented Mar 21, 2022

@forsureitsme I mean, yeah, sure, but I wanted to simulate a situation where I'd have nothing but cons. The reason I'm using JS here is for accessibility. Concatenation is a non-trivial op if you're working with lists.

These implementations aren't meant to be good or efficient, just show that even if all you can do is prepend you can build map and filter just using reduce.

Also, these are theoretical implementations! We can do a lot better than either yours or mine if we actually want to build something JS-friendly (probably using internal mutation) :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment