Skip to content

Instantly share code, notes, and snippets.

@taiju
Created August 27, 2012 13:57
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save taiju/3488667 to your computer and use it in GitHub Desktop.
partition method full params for underscore.js
var partitionIterator = function(array, n, step, pad, is_all, result) {
if (_.size(array) < n) {
if (_.isNull(pad) && is_all) return (_.isEmpty(array)) ? result : result.concat([array]);
else if (!_.isNull(pad) && !is_all) return result.concat([array.concat(_.take(pad, n - _.size(array)))]);
else return result;
}
else return partitionIterator(_.rest(array, step), n, step, pad, is_all, result.concat([_.take(array, n)]));
};
_.mixin({
partition: function(array, n, step, pad) {
var is_all = false, result = [];
if (!_.isNumber(n)) throw new TypeError;
if (!_.isUndefined(step) && !_.isNumber(step)) throw TypeError;
if (!_.isUndefined(pad) && !_.isArray(pad)) throw TypeError;
step = step ? step : n;
pad = pad ? pad : null;
return partitionIterator(array, n, step, pad, is_all, result);
},
partitionAll: function(array, n, step) {
var pad = null, is_all = true, result = [];
if (!_.isNumber(n)) throw new TypeError;
if (!_.isUndefined(step) && !_.isNumber(step)) throw TypeError;
step = step ? step : n;
return partitionIterator(array, n, step, pad, is_all, result);
}
});
/**
* Refs:
* partition -> http://clojuredocs.org/clojure_core/clojure.core/partition
* partitionAll -> http://clojuredocs.org/clojure_core/clojure.core/partition-all
*/
_.partition(_.range(10), 3); // -> [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
_.partition(_.range(10), 3, 2); // -> [[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8]]
_.partition(_.range(10), 4, 4, [1, 2, 3]); // -> [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 1, 2]]
_.partitionAll(_.range(10), 3); // -> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
_.partitionAll(_.range(10), 3, 2); // -> [[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8], [8, 9]]
_.partitionAll(_.range(10), 2); // [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment