Last active
October 12, 2022 11:13
-
-
Save Ivannnnn/b230932592f29e1f40c3bde3c119dc86 to your computer and use it in GitHub Desktop.
Some functional programming functions
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 SORT_STRATEGIES = { | |
asc: (a, b) => (a - b > 0 ? 1 : -1), | |
desc: (a, b) => (a - b < 0 ? 1 : -1), | |
}; | |
const pipe = (...fns) => | |
fns.reduce( | |
(f, g) => | |
(...args) => | |
g(f(...args)) | |
); | |
const map = | |
(...funcs) => | |
(arr) => | |
arr.map(pipe(...funcs)); | |
const filter = | |
(...funcs) => | |
(arr) => | |
arr.filter((val) => funcs.every((func) => func(val))); | |
const sortBy = | |
(key = false, ascOrDesc = "asc") => | |
(arr) => { | |
return [...arr].sort((a, b) => | |
SORT_STRATEGIES[ascOrDesc](key ? a[key] : a, key ? b[key] : b) | |
); | |
}; | |
const take = (x) => (arr) => arr.slice(0, x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment