Skip to content

Instantly share code, notes, and snippets.

@Cfeusier
Last active January 31, 2016 11:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Cfeusier/e2d065c2216dacba2806 to your computer and use it in GitHub Desktop.
Save Cfeusier/e2d065c2216dacba2806 to your computer and use it in GitHub Desktop.
2kb unminified/unzipped drop-in for the usual utility functions
var underramdash = {
each: each,
map: map,
reduce: reduce,
filter: filter,
flatten: flatten,
uniq: uniq,
extend: extend,
every: every,
identity: identity
};
module.exports = underramdash;
function each(collection, iterator) {
if (Array.isArray(collection)) {
collection.forEach(function(item, i) {
iterator(item, i, collection);
});
} else {
for (var key in collection) {
if (collection.hasOwnProperty(key)) {
iterator(collection[key], key, collection);
}
}
}
}
function map(collection, callback) {
var mapped = [];
each(collection, function(item) {
mapped.push(callback(item));
});
return mapped;
}
function reduce(collection, iterator, accumulator) {
var initd = arguments.length === 3;
each(collection, function(value) {
if (!initd) {
accumulator = value;
initd = true;
} else {
accumulator = iterator(accumulator, value);
}
});
return accumulator;
}
function filter(collection, predicate) {
var filtered = [];
each(collection, function(item) {
if (predicate(item)) {
filtered.push(item);
}
});
return filtered;
}
function flatten(mdArray, fltArray) {
fltArray = fltArray || [];
each(mdArray, function(item) {
Array.isArray(item) ? flatten(item, fltArray) : fltArray.push(item);
});
return fltArray;
}
function uniq(dupeArray) {
var deDupedHisto = {},
deDupedResults = [];
each(dupeArray, function(value) {
deDupedHisto[value] = value;
});
each(deDupedHisto, function(item) {
deDupedResults.push(item);
});
return deDupedResults;
}
function extend(destObj) {
for (var i = 1; i < arguments.length; i++) {
var sourceObj = arguments[i];
each(sourceObj, function(item, key) {
destObj[key] = item;
});
}
return destObj;
}
function every(collection, predicate) {
predicate = predicate || identity(predicate);
return !!reduce(collection, function(trueSoFar, value) {
return trueSoFar && predicate(value);
}, true);
}
function identity() {
return function(value) {
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment