Advanced Left-To-Right Function Composer
// NO! Pyramid of DOOM! Reversed Process Order!
const foo = doLastThing(
doThirdThing(
doSecondThing(
doFirstThing(a, b, c)
)
)
);
// YES! Clear, Ordered Steps!
const thingsToDo = [
doFirstThing,
doSecondThing,
doThirdThing,
doLastThing
];
// To Function!
const doSomeThings = toFun(thingsToDo);
// And Done!
const foo = doSomeThings(a, b, c);
const doSomeThings = toFun(
doFirstThing,
doSecondThing,
doThirdThing,
doLastThing
);
const foo = doSomeThings(a, b, c);
to-fun
understands promises!
const findUserByName = (name) => {
return db.users.findOne({name})
};
const activateUser = (user) => ({
...user,
activated: true
});
// To Function!
const activateByName = toFun(findUserByName, activateUser, db.users.update);
// Invoke and catch errors like usual
activateByName('Jesse').catch(errorHandler);
to-fun
supports nested composition!
const access = [readSession, checkPermissions ]
const sanitizeForm = [ sanitizeXss, sanitizeSqlInject ]
const validateForm = [ checkNonce, validateComment]
const clean = [sanitizeForm, validateForm];
// clearly-defined flow
on('add-comment', toFun(
access,
clean,
db.comments.insert,
respondOk
)).catch(respondWithError);
Installation (npm):
npm install --save to-fun
For the import
-ers:
import f from 'to-fun';
For the require
-ers:
var f = require('to-fun').default;