Created
January 25, 2016 21:06
-
-
Save noxecane/39f9fe0d1c59a2169d6e to your computer and use it in GitHub Desktop.
Some functions I use daily for functional programming.(most of them from Javascript Allonge)
This file contains hidden or 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
'use strict'; | |
export const isNothing = x => x === null || x === undefined; | |
// iterations | |
export const repeat = (num, fn) => (num > 0) ? | |
(repeat(num - 1, fn), fn(num - 1)) : | |
(void 0); | |
// Decorators | |
export const not = f => (...args) => !f(...args); | |
export const partialLeft = (fn, ...mainArgs) => | |
(...restArgs) => | |
fn(...mainArgs, ...restArgs); | |
export const partialRight = (fn, ...mainArgs) => | |
(...restArgs) => | |
fn(...restArgs, ...mainArgs); | |
export const compose = (a, b) => | |
(...args) => a(b(...args)); | |
export const unary = fn => | |
fn.length === 1 ? | |
fn : | |
function (something) { | |
fn.call(this, something); | |
}; | |
export const once = fn => { | |
let done = false; | |
return function (...args) { | |
return done ? void 0 : ((done = true), fn.apply(this, args)); | |
}; | |
}; | |
// monads | |
export const maybe = (fn, test=isNothing) => function (...args) { | |
if (args.length === 0) { | |
return; | |
} else { | |
if (args.every(test)) { | |
return; | |
} | |
return fn.apply(this, args); | |
} | |
}; | |
export const bind = (a, b) => (...args) => { | |
let result = b(...args); | |
return result ? | |
a(result) : | |
void 0; | |
}; | |
// TODO support for finally clause | |
export const doP = f => { | |
let gen = f(); | |
return new Promise((resolve, reject) => { | |
if (gen && typeof gen.next !== 'function') { | |
resolve(gen); | |
} | |
step(); | |
function step(previousResult) { | |
let result; | |
try { | |
result = gen.next(previousResult); | |
} catch (e) { | |
return reject(e); | |
} | |
next(result); | |
} | |
function stump(error) { | |
var result; | |
try { | |
result = gen.throw(error); | |
} catch (e) { | |
return reject(e); | |
} | |
next(result); | |
} | |
function next(result) { | |
if (result.done) { | |
return resolve(result.value); | |
} | |
if (result.value instanceof Promise) { | |
result.value.then(step, stump); | |
} else { | |
setTimeout(step, 0, result.value); | |
} | |
} | |
}); | |
}; | |
export const asyncP = genFunc => { | |
return (...args) => { | |
doP(() => genFunc(...args)); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment