I'm constructing a Builder in JavaScript, and I'm not sure how builders normally handle undefined values for optionals. I would like to think that the Builder doesn't append the optional field to the object if the field is undefined. Here is a sample:
Builder:
function Thing(required1, required2, required3) {
//check required params
var fields = {
required1: required1,
required2: required2,
required3: required3
};
var _withOptionalParam = function(param) {
if(!param) { return this; } //exit function early if param is undefined
fields.param = param;
return this;
};
var builder = {
withOptionalParam: _withOptionalParam
};
return builder;
}
In action:
var thing = new Thing("foo","bar","baz").withOptionalParam(undefined);
//'thing' should be
{
required1:"foo",
required2:"bar",
required3:"baz"
};
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire