Skip to content

Instantly share code, notes, and snippets.

@soarez
Created June 10, 2014 15:54
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 soarez/d3454d43238610910270 to your computer and use it in GitHub Desktop.
Save soarez/d3454d43238610910270 to your computer and use it in GitHub Desktop.
Match elements from two arrays according to a specific criteria and obtain missing and extraneous elements.
var known = [ 1, 6, 3, 9, 4 ];
var presented = [ 2, 5, 7, 4, 9, 4 ];
check(known, presented, match, done);
function match(k, p) {
if( k !== p) return false;
console.log(k, 'matched with', p);
return true;
}
function done(missing, extraneous) {
console.log('Missing:', missing);
console.log('Extraneous:', extraneous);
}
function check(known, presented, match, done) {
var extraneous = presented.slice();
var missing = known.filter(unmatched);
return done(missing, extraneous);
function unmatched(k) {
return ! extraneous.some(matches);
function matches(p) {
if (! match(k, p)) return false;
extraneous.splice(extraneous.indexOf(p), 1);
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment