Adding _.defaults, Issue #106

This commit is contained in:
Jeremy Ashkenas
2011-02-01 21:19:58 -05:00
parent d0faeb53c1
commit 226b7d9344
3 changed files with 37 additions and 1 deletions

View File

@@ -167,7 +167,7 @@
<b>Objects</b>
<br />
<span class="methods"><a href="#keys">keys</a>, <a href="#values">values</a>,
<a href="#functions">functions</a>, <a href="#extend">extend</a>, <a href="#clone">clone</a>, <a href="#tap">tap</a>,
<a href="#functions">functions</a>, <a href="#extend">extend</a>, <a href="#defaults">defaults</a>, <a href="#clone">clone</a>, <a href="#tap">tap</a>,
<a href="#isEqual">isEqual</a>, <a href="#isEmpty">isEmpty</a>, <a href="#isElement">isElement</a>,
<a href="#isArray">isArray</a>, <a href="#isArguments">isArguments</a>, <a href="#isFunction">isFunction</a>, <a href="#isString">isString</a>,
<a href="#isNumber">isNumber</a>, <a href="#isBoolean">isBoolean</a>, <a href="#isDate">isDate</a>, <a href="#isRegExp">isRegExp</a>
@@ -815,6 +815,19 @@ _.functions(_);
<pre>
_.extend({name : 'moe'}, {age : 50});
=&gt; {name : 'moe', age : 50}
</pre>
<p id="defaults">
<b class="header">defaults</b><code>_.defaults(object, *defaults)</code>
<br />
Fill in missing properties in <b>object</b> with default values from the
<b>defaults</b> objects. As soon as the property is filled, further defaults
will have no effect.
</p>
<pre>
var iceCream = {flavor : "chocolate"};
_.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"});
=&gt; {flavor : "chocolate", sprinkles : "lots"}
</pre>
<p id="clone">

View File

@@ -26,6 +26,21 @@ $(document).ready(function() {
ok(_.isEqual(result, {x:2, a:'b'}), 'extending from multiple source objects last property trumps');
});
test("objects: defaults", function() {
var result;
var options = {zero: 0, one: 1, empty: "", nan: NaN, string: "string"};
_.defaults(options, {zero: 1, one: 10, twenty: 20});
equals(options.zero, 0, 'value exists');
equals(options.one, 1, 'value exists');
equals(options.twenty, 20, 'default applied');
_.defaults(options, {empty: "full"}, {nan: "nan"}, {word: "word"}, {word: "dog"});
equals(options.empty, "", 'value exists');
ok(_.isNaN(options.nan), "NaN isn't overridden");
equals(options.word, "word", 'new value is added, first one wins');
});
test("objects: clone", function() {
var moe = {name : 'moe', lucky : [13, 27, 34]};
var clone = _.clone(moe);

View File

@@ -525,6 +525,14 @@
return obj;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) if (obj[prop] == null) obj[prop] = source[prop];
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);