Skip to content

Instantly share code, notes, and snippets.

@tsouk
Last active November 1, 2017 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsouk/ea36798b393530334da3de66a9176b46 to your computer and use it in GitHub Desktop.
Save tsouk/ea36798b393530334da3de66a9176b46 to your computer and use it in GitHub Desktop.
Some functional JS we like
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x); //x = form
const curry = fn => (...args) => fn.bind(null, ...args);
const map = curry((fn, arr) => arr.map(fn));
const join = curry((str, arr) => arr.join(str));
const toLowerCase = str => str.toLowerCase();
const split = curry((splitOn, str) => str.split(splitOn));
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const tap = curry((fn, x) => {
fn(x);
return x;
});
const trace = curry((label, x) => {
console.log(`== ${ label }: ${ x }`);
return x;
});
// or write it a a special tap
const trace = label => {
return tap(x => console.log(`== ${ label }: ${ x }`));
};
const toSlug = pipe(
trace('input'),
split(' '),
map(toLowerCase),
trace('after map'),
join('-'),
encodeURIComponent
);
console.log(toSlug('JS Cheerleader'));
// '== input: JS Cheerleader'
// '== after map: js,cheerleader'
// 'js-cheerleader'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment