Skip to content

Instantly share code, notes, and snippets.

@gerardpaapu
Created April 1, 2012 23:48
Show Gist options
  • Select an option

  • Save gerardpaapu/2279530 to your computer and use it in GitHub Desktop.

Select an option

Save gerardpaapu/2279530 to your computer and use it in GitHub Desktop.
// Me circa April 2009
Array.implement({
"collect": function collect(fn, bind) {
// fn.calls that throw an exception are
// excluded and the index is not incremented
// so that it's like they were never there.
// can be used instead of a.map( ... ).filter( ... )
// --------------------------------------------------
// Throwing is quite slow though, so you'd only really
// want to use it when fn is already throwing errors IMO
var results = [];
var j = 0;
for (var i = 0, l = this.length; i < l; i++ ){
try {
results[j] = fn.call(bind, this[i], j, this);
j++;
} catch (err) {}
}
return results;
}
});
// Me today (Apr 2012)
Array.implement({
collect: function collect(fn, ctx) {
// The bastard child of `map` and `filter`
// `fn` is called with `fn.call(ctx, item, index, array, SKIP)`
//
// item: the current item of from the source array
// index: the current index in the results
// array: the source array (AKA `this`)
// SKIP: if fn returns `SKIP`, nothing is added to the results
var results = [],
SKIP = {},
result, i, index, max;
for (i = 0, max = this.length; i < max; i++) {
index = results.length;
result = fn.call(ctx, this[i], index, this, SKIP);
if (result !== SKIP) results[index] = result;
}
return results;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment