Created
June 10, 2014 15:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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