Created
March 19, 2022 23:24
-
-
Save coproduto/3a0d345b315e270adf144e4edb59a497 to your computer and use it in GitHub Desktop.
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
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 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
The array reversing in
map
andfilter
could be skipped by concatenating with the spread syntax.