Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Last active August 29, 2015 14:01
Show Gist options
  • Save jussi-kalliokoski/76d02cb80c8a2c2def86 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/76d02cb80c8a2c2def86 to your computer and use it in GitHub Desktop.
Natural language constructs in JS
var createSentence = function () {
var names = [].slice.call(arguments);
var fn = names.pop();
if ( names.length === 0 ) {
return fn;
}
var name = names.shift();
return function (value) {
var obj = {};
obj[name] = createSentence.apply(null, names.concat(fn.bind(null, value)));
return obj;
};
};
describe("createSentence", function () {
it("should create a one-level chain given one name", function () {
var combine = createSentence("with", function (a, b) {
return a + " " + b;
});
combine("foo").with("bar").should.equal("foo bar");
});
it("should create a two-level chain given two names", function () {
var createPerson = createSentence("withFirstName", "withLastName", function (nickName, firstName, lastName) {
return {
nickName: nickName,
firstName: firstName,
lastName: lastName
};
});
createPerson("blackjack").withFirstName("Jack").withLastName("Black").should.deep.equal({
nickName: "blackjack",
firstName: "Jack",
lastName: "Black"
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment