Skip to content

Instantly share code, notes, and snippets.

@billychan
Last active August 29, 2015 13:56
Show Gist options
  • Save billychan/9036746 to your computer and use it in GitHub Desktop.
Save billychan/9036746 to your computer and use it in GitHub Desktop.
custom _.results() function
// 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;
};
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