Skip to content

Instantly share code, notes, and snippets.

@ivanoats
Created December 8, 2015 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanoats/65d2265363201f62fdfe to your computer and use it in GitHub Desktop.
Save ivanoats/65d2265363201f62fdfe to your computer and use it in GitHub Desktop.
Pluck, Unique, and Compose from scratch in JS
function pluck(property, collection) {
return collection.map(function(e){
return e[property];
});
}
// return an array with unique elements
// this isn't efficient for sorted arrays, but whatevs
function unique(collection) {
// ternary operator to guard for empty collection
var length = collection ? collection.length : 0;
if (!length) { return []; }
var seen = [];
collection.forEach(function(e) {
if ( seen.indexOf(e) < 0 ) { seen.push(e); }
});
return seen;
}
// compose two functions together
function compose(func1, func2) {
return function() {
return func1(func2.apply(null, arguments));
};
}
var distinct = compose(unique, pluck);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment