Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created January 20, 2009 11:05
Show Gist options
  • Save atifaziz/49432 to your computer and use it in GitHub Desktop.
Save atifaziz/49432 to your computer and use it in GitHub Desktop.
JavaScript map, reduce, group, distinct
Object.properties = function(obj, includeFunctions)
{
var props = [];
for (var prop in obj)
{
if (true === includeFunctions || 'function' !== typeof obj[prop])
props.push(prop);
}
return props;
}
Array.prototype.reduce = function(acc, callback/*(accumulator, element, index)*/, finalizer)
{
for (var i = 0; i < this.length; i++)
acc = callback(acc, this[i], i);
return 'function' === typeof finalizer ? finalizer(acc) : acc;
}
Array.prototype.map = function(callback/*(element, index)*/)
{
return this.reduce([], function(arr, e, i) { arr.push(callback(e, i)); return arr; });
}
Array.prototype.group = (function()
{
function Grouping() { }
Grouping.prototype.keys = function() { return Object.properties(this); };
return function(fkey/*(element, index)*/, fvalue/*(element, index)*/)
{
if ('function' !== typeof fvalue)
fvalue = function(e) { return e; };
return this.reduce(
new Grouping(),
function(grouping, e, i)
{
var key = fkey(e, i);
if (!(key in grouping))
{
var g = [];
g.key = key;
grouping[key] = g;
}
grouping[key].push(fvalue(e, i));
return grouping;
}
);
};
})();
Array.prototype.distinct = function(callback/*(element, index)*/)
{
return this.group('function' === typeof callback ? callback : function(e) { return e; }).keys();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment