Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active October 12, 2022 11:13
Show Gist options
  • Save Ivannnnn/b230932592f29e1f40c3bde3c119dc86 to your computer and use it in GitHub Desktop.
Save Ivannnnn/b230932592f29e1f40c3bde3c119dc86 to your computer and use it in GitHub Desktop.
Some functional programming functions
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