Last active
August 29, 2015 14:14
-
-
Save der-On/98b438ec21ae471cc1c7 to your computer and use it in GitHub Desktop.
Chainable formatters
This file contains 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"; | |
/* | |
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