Created
February 28, 2015 17:56
-
-
Save aldraco/3c28733baa1e83bfbafb to your computer and use it in GitHub Desktop.
symmetric diff bonfire (WIP)
This file contains 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
function sym(arr) { | |
//get args | |
var args = Array.prototype.slice.call(arguments); | |
//symmetric difference is the union minus the intersection | |
//find the union with no duplicates | |
function findUnion (arr1, arr2) { | |
var union = (arr1.concat(arr2)).sort(); | |
//steps through the values to remove dups | |
for (var i = union[0]; i < union[union.length-1]; i++) { | |
//for each value, are there duplicates? | |
if (union.indexOf(i) >= 0) { | |
if (union.indexOf(i) !== union.lastIndexOf(i)) { | |
// remove all but the first one | |
var firstIndex = union.indexOf(i); | |
var howMany = (union.lastIndexOf(i) - firstIndex); | |
union.splice(firstIndex+1, howMany); | |
} | |
} | |
} | |
return union; | |
} | |
function findIntersection (arr1, arr2) { | |
//find the intersection | |
var intersection = []; | |
//step through arr1, looking for each element in arr2 | |
arr1.forEach(function(value, index) { | |
if (compare(value, arr2)>=0) { | |
if (intersection.indexOf(value)) { | |
intersection.push(value); | |
} | |
} | |
}); | |
// helper function for above | |
function compare(value, arr) { | |
return (arr.indexOf(value) >= 0); | |
} | |
return intersection; | |
} | |
var union = findUnion(args[0], args[1]); | |
var intersection = findIntersection(args[0], args[1]); | |
console.log(union, intersection); | |
var symmDiff; | |
//filter union for intersection to return symm diff | |
symmDiff = union.filter(function(value, index) { | |
console.log(intersection.indexOf(value)); | |
return (intersection.indexOf(value) < 0); | |
}); | |
return symmDiff; | |
} | |
sym([1, 1], [1]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment