From 226b7d93448468f7d2133e89c438fdcd283d24be Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Tue, 1 Feb 2011 21:19:58 -0500 Subject: [PATCH] Adding _.defaults, Issue #106 --- index.html | 15 ++++++++++++++- test/objects.js | 15 +++++++++++++++ underscore.js | 8 ++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index 41951b650..74dc362c7 100644 --- a/index.html +++ b/index.html @@ -167,7 +167,7 @@ Objects
keys, values, - functions, extend, clone, tap, + functions, extend, defaults, clone, tap, isEqual, isEmpty, isElement, isArray, isArguments, isFunction, isString, isNumber, isBoolean, isDate, isRegExp @@ -815,6 +815,19 @@ _.functions(_);
 _.extend({name : 'moe'}, {age : 50});
 => {name : 'moe', age : 50}
+
+ +

+ defaults_.defaults(object, *defaults) +
+ Fill in missing properties in object with default values from the + defaults objects. As soon as the property is filled, further defaults + will have no effect. +

+
+var iceCream = {flavor : "chocolate"};
+_.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"});
+=> {flavor : "chocolate", sprinkles : "lots"}
 

diff --git a/test/objects.js b/test/objects.js index f0a60ecfe..d4bfac645 100644 --- a/test/objects.js +++ b/test/objects.js @@ -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); diff --git a/underscore.js b/underscore.js index bd37e148b..5aaaca372 100644 --- a/underscore.js +++ b/underscore.js @@ -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);