Skip to content

Instantly share code, notes, and snippets.

@der-On
Last active August 29, 2015 14:14
Show Gist options
  • Save der-On/98b438ec21ae471cc1c7 to your computer and use it in GitHub Desktop.
Save der-On/98b438ec21ae471cc1c7 to your computer and use it in GitHub Desktop.
Chainable formatters
"use strict";
/*
Chainable formatters
Usage:
function trim(value) {
return value.trim();
}
function append(str) {
return function(value) {
return value + str;
}
}
f(' foo ').p(trim).p(append('bar')).exec(); > foobar
or with lazy rendering
var chain = f().p(trim).p(append('bar'));
chain.exec(' foo '); > foobar
chain.exec(' baz '); > bazbar;
*/
function f(value) {
this.value = value || null;
}
f.prototype = new Array();
// create aliases for native push method
f.prototype.pipe = f.prototype.p = Array.prototype.push;
// add execute method
f.prototype.e = f.prototype.exec = function(value) {
return this.reduce(function(prev, curr, index) {
return curr(prev);
}, value || this.value || null);
};
module.exports = function(value) {
return new f(value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment