Last active
August 29, 2015 13:56
-
-
Save billychan/9036746 to your computer and use it in GitHub Desktop.
custom _.results() function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Iterates an one level object with functions inside and return invoked values | |
// This was an unmerged PR by me https://github.com/jashkenas/underscore/pull/1482 | |
// Patch it in a Backbone project when needed. | |
_.results = function(object, context) { | |
if (typeof context == "undefined") { | |
context = object; | |
}; | |
var copy = {}; | |
_.each(object, function(value, key) { | |
var v = _.isFunction(value) ? value.call(context) : value; | |
copy[key] = v; | |
}); | |
return copy; | |
}; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test('_.results iterates an object with function and return invoked results', function() { | |
var obj = {w: '', x: 'x', y: function(){ return this.x; }}; | |
var results = _.results(obj) | |
strictEqual(results.w, ''); | |
strictEqual(results.x, 'x'); | |
strictEqual(results.y, 'x'); | |
var contextObj = {x: '_x'} | |
var results = _.results(obj, contextObj) | |
strictEqual(results.w, ''); | |
strictEqual(results.x, 'x'); | |
strictEqual(results.y, '_x'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment