Created
April 2, 2014 12:02
-
-
Save xuyang2/9932749 to your computer and use it in GitHub Desktop.
underscore mixins
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
_.mixin({ | |
/** | |
* Iterates over an array of numbers and returns the sum. Example: | |
* | |
* var sum = _.sum([1, 2, 3]); | |
* => 6 | |
* | |
* @param obj | |
* @returns {Number} | |
*/ | |
sum: function (obj) { | |
if (!_.isArray(obj) || obj.length == 0) { | |
return 0; | |
} | |
return _.reduce(obj, function (memo, num) { | |
return memo + num; | |
}, 0); | |
}, | |
/** | |
* var mul = _.mul([1, 2, 3]); | |
* => 6 | |
* | |
* @param obj | |
* @returns {Number} | |
*/ | |
mul: function (obj) { | |
if (!_.isArray(obj) || obj.length == 0) { | |
return 0; | |
} | |
return _.reduce(obj, function (memo, num) { | |
return memo * num; | |
}, 1); | |
}, | |
/** | |
* _.chunk([2,3,4,5], 2); | |
* => [[2,3],[4,5]] | |
* | |
* @param array | |
* @param unit | |
* @returns {*} | |
*/ | |
chunk: function (array, unit) { | |
if (!_.isArray(array)) return array; | |
unit = Math.abs(unit); | |
var results = [], | |
length = Math.ceil(array.length / unit); | |
for (var i = 0; i < length; i++) { | |
results.push(array.slice(i * unit, (i + 1) * unit)); | |
} | |
return results; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment