Skip to content

Instantly share code, notes, and snippets.

@JasonStoltz
Created March 31, 2015 18:13
Show Gist options
  • Save JasonStoltz/f3330fa009cdd6607212 to your computer and use it in GitHub Desktop.
Save JasonStoltz/f3330fa009cdd6607212 to your computer and use it in GitHub Desktop.
Javascript Builder pattern for function
function makeSoup(base){
var ingredients = {
base: base
};
var options = {
withMushrooms: function(){
ingredients.mushrooms = true;
return this;
},
withOnions: function(){
ingredients.onions = true;
return this;
},
withBeans: function(){
ingredients.beans = true;
return this;
},
go: function(){
var extras = [];
if (ingredients.mushrooms) extras.push('mushrooms');
if (ingredients.onions) extras.push('onions');
if (ingredients.beans) extras.push('beans');
return {
base: base,
extras: extras,
taste: extras.length
};
}
}
return options;
}
console.log(makeSoup('chicken').withMushrooms().withOnions().go());
console.log(makeSoup('vegetables').go());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment