Property defaults

#1 · closed · 2 comments

View on GitHub ↗

rwaldron

Case: ``` js var sources = [ { modes: [0, 1, 4] }, { modes: [0, 1, 2], analogChannel: 0 } ]; var mapping = { supportedModes: "modes", analogChannel: "analogChannel" }; sources.forEach(function(source) { console.log( remapped(source, mapping) ); }); ``` Correctly produces: ``` { supportedModes: [ 0, 1, 4 ], analogChannel: undefined } { supportedModes: [ 0, 1, 2 ], analogChannel: 0 } ``` However, it might be desirable to provide a default value that's used when the corresponding property is undefined. This should apply to "missing" and explicit undefined, eg. ``` js var sources = [ { modes: [0, 1, 4] }, { modes: [0, 1, 2], analogChannel: undefined } ]; var mapping = { supportedModes: "modes", analogChannel: { key: "analogChannel", default: null } }; sources.forEach(function(source) { console.log( remapped(source, mapping) ); }); ``` Produces: ``` { supportedModes: [ 0, 1, 4 ], analogChannel: null } { supportedModes: [ 0, 1, 2 ], analogChannel: null } ``` The recommendation to use implied or explicit undefined rationally matches ES6 default parameter values: ``` js function f(a = 1) { return a; } a(); // 1 a(undefined); // 1 ```

Comments

tkellen

This is a cool idea! Putting the defaults inline on the mapping would break the simplicity of this module, but defining them as a separate object would totally work. I'll publish something after this call.

tkellen

v0.3.0 on npm supports an optional defaults object--lemme know if it works for ya?