Skip to content

Instantly share code, notes, and snippets.

@clementi clementi/iterable.js
Created Nov 18, 2010

Embed
What would you like to do?
var Iterable = {
func: {
predicate: {
TRUE: function (x) { return true; }
}
}
};
Array.prototype.forEach = function (fn) {
for (var i = 0; i < this.length; i++)
fn(this[i]);
};
Array.prototype.filter = function (pred) {
var result = [];
this.forEach(function (x) {
if (pred(x))
result.push(x);
});
return result;
};
Array.prototype.distinct = function () {
var result = [];
this.forEach(function (x) {
if (!result.any(function (y) { return y == x; }))
result.push(x);
});
return result;
};
Array.prototype.any = function (pred) {
pred = pred || Iterable.func.predicate.TRUE;
for (var i = 0; i < this.length; i++)
if (pred(this[i]))
return true;
return false;
};
Array.prototype.indexOf = function (expr) {
if (!(expr instanceof Function))
expr = function (x) { return x == expr; };
for (var i = 0; i < this.length; i++)
if (expr(this[i]))
return i;
return -1;
};
Array.prototype.singleOrNull = function (pred) {
var filtered = this.filter(pred);
if (filtered.length == 0)
return null;
if (filtered.length > 1)
throw "More than one element returned.";
return filtered[0];
};
Array.prototype.map = function (fn) {
var mapped = [];
this.forEach(function (x) { mapped.push(fn(x)); });
return mapped;
};
Array.prototype.groupBy = function (sel) {
var groups = [];
this.forEach(function (x) {
var group = groups.singleOrNull(function (y) { return y.key == sel(x); });
if (!group)
groups.push({ key: sel(x), members: [x] });
else
group.members.push(x);
});
return groups;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.