Skip to content

Instantly share code, notes, and snippets.

@webbower
Last active April 18, 2018 16:42
Show Gist options
  • Save webbower/1749442ee7ac77d8a196db63c39cab55 to your computer and use it in GitHub Desktop.
Save webbower/1749442ee7ac77d8a196db63c39cab55 to your computer and use it in GitHub Desktop.
// trace() is a utility to let you easily inspect
// the contents.
const trace = x => {
console.log(x);
return x;
};
const tap = (fn, tapper) => (...args) => {
const result = fn(...args);
tapper(result);
return result;
};
const sequence = (...fns) => x => fns.forEach(fn => fn(x));
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
const pipeWrap = (wrapper, piper = pipe) => (...fns) => piper(...fns.map(wrapper));
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);
const composePredicatesAnd = (...preds) => x => preds.reduceRight((lastTest, pred) => lastTest && pred(x));
const composePredicatesOr = (...preds) => x => preds.reduceRight((lastTest, pred) => lastTest || pred(x), false);
const composeWrap = (wrapper, composer = compose) => (...fns) => composer(...fns.map(wrapper));
const thunkify = (fn, ...args) => () => fn(...args);
const promisifySync = fn => (...args) => {
try {
return Promise.resolve(fn(...args));
} catch(err) {
return Promise.reject(err);
}
};
const promisifySync2 = fn => (...args) => new Promise((resolve, reject) => {
try {
resolve(fn(...args));
} catch(error) {
reject(error);
}
};
const promisifyAsync = fn => (...args) =>
new Promise((resolve, reject) =>
fn(...args.concat((error, result) => (error ? reject(error) : resolve(result))));
)
;
// https://casualjavascript.com/index.html?1
/**
* Applies a function which is passed as the second argument to
* the third argument and it comapares the result with the condition,
* if the condition evaluates to true, it prints the result, if not,
* it passes the result to the function and repeats the cycle as long
* as the condition is matched
* @param condition condition to be applied to f
* @param f function to match against
* @return result if condition is true else repeat cycle
**/
export function until (condition, f) {
return (...args) => {
var r = f(...args);
return condition(r) ? r : until(condition, f)(r);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment