Skip to content

Instantly share code, notes, and snippets.

@mmacedo
Created December 28, 2014 19:45
Show Gist options
  • Save mmacedo/213bd52b2965ce681103 to your computer and use it in GitHub Desktop.
Save mmacedo/213bd52b2965ce681103 to your computer and use it in GitHub Desktop.
Lazy = _.chain;
Lazy.range = function() {
return _.chain(_.range.apply(_, arguments));
};
_.prototype.toArray = function() {
return this.value();
};
var originalFlatten = _.prototype.flatten;
_.prototype.flatten = function() {
var arr = this.map(function(x){
return typeof x.value === 'function' ? x.value() : x;
});
return originalFlatten.call(arr);
}
var originalSortBy = _.prototype.sortBy;
_.prototype.sortBy = function(foo, reverse) {
var arr = originalSortBy.call(this, foo);
return reverse ? arr.reverse() : arr;
}
_.prototype.sum = function(foo) {
return this.reduce(function(memo, num) {
return memo + (typeof foo === 'function' ? foo(num) : num);
}, 0).value();
};
_.prototype.chunk = function(size) {
return _.chain(this.reduce(function(memo, num) {
if (memo.length === 0) {
return [[num]];
} else {
var lastArr = memo[memo.length - 1];
if (lastArr.length < size) {
lastArr.push(num);
} else {
memo.push([num]);
}
}
return memo;
}, []));
};
_([ 'find', 'some', 'every' ]).each(function(foo) {
var original = _.prototype[foo];
_.prototype[foo] = function() {
return original.apply(this, arguments).value();
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment