Skip to content

Instantly share code, notes, and snippets.

@acjr1910
Last active August 19, 2020 23:12
Show Gist options
  • Save acjr1910/58b2ad7d69d42199d2f640fc6f55c62b to your computer and use it in GitHub Desktop.
Save acjr1910/58b2ad7d69d42199d2f640fc6f55c62b to your computer and use it in GitHub Desktop.
fp-lib
function curry(arity, fn) {
return (function nextCurried(prevArgs) {
return function curried(nextArg) {
var args = prevArgs.concat([nextArg]);
if (args.length >= arity) {
return fn(...args);
} else {
return nextCurried(args);
}
};
})([]);
}
function compose(...fns) {
return pipe(...fns.reverse());
}
function pipe(...fns) {
return function piped(result) {
for (let fn of fns) {
result = fn(result);
}
return result;
};
}
function mapObj(mapperFn, o) {
var newObj = {};
var keys = Object.keys(o);
for (let key of keys) {
newObj[key] = mapperFn(o[key]);
}
return newObj;
}
function filterObj(predicateFn, o) {
var newObj = {};
var keys = Object.keys(o);
for (let key of keys) {
if (predicateFn(o[key])) newObj[o[key]] = o[key];
}
return newObj;
}
function reduceObj(reducerFn, initialValue, o) {
var result = initialValue;
var keys = Object.keys(o);
for (let key of keys) {
result = reducerFn(result, o[key]);
}
return result;
}
function pathOr(or, arrPath, obj) {
if (!arrPath.length || !obj) return or || "";
return arrPath.reduce((accObj, value) => {
if (typeof accObj === "object" && value in accObj) {
return accObj[value];
}
return or;
}, obj);
}
function functor(value) {
return {
map: identity(fn => fn(value)),
fold: fn => fn(value),
log: () => `log: ${value}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment