Last active
August 29, 2015 14:20
-
-
Save linus-amg/faeeff52dbca3cc7ca95 to your computer and use it in GitHub Desktop.
Deepsum.js
This file contains 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
Handlebars.registerHelper('deepSum', function(source, key) { | |
var result; | |
if (typeof key === 'string') { | |
if (key.split('.').length > 1) { | |
source = _.pluckDeep(source, key); | |
} else { | |
source = _.pluck(source, key); | |
} | |
} | |
return result = _.reduce(source, function(memo, num) { | |
return memo + num; | |
}); | |
}); | |
// underscore.deep.js | |
_.mixin({ | |
deep: function (obj, key, value) { | |
var keys = key.replace(/\[(["']?)([^\1]+?)\1?\]/g, '.$2').replace(/^\./, '').split('.'), | |
root, | |
i = 0, | |
n = keys.length; | |
if (arguments.length > 2) { | |
root = obj; | |
n--; | |
while (i < n) { | |
key = keys[i++]; | |
obj = obj[key] = _.isObject(obj[key]) ? obj[key] : {}; | |
} | |
obj[keys[i]] = value; | |
value = root; | |
} else { | |
while ((obj = obj[keys[i++]]) != null && i < n) {}; | |
value = i < n ? void 0 : obj; | |
} | |
return value; | |
} | |
}); | |
_.mixin({ | |
pluckDeep: function (obj, key) { | |
return _.map(obj, function (value) { return _.deep(value, key); }); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment