Last active
August 29, 2015 14:17
-
-
Save jremmen/1b8d4f6e378f7d765e57 to your computer and use it in GitHub Desktop.
js: recursive 2 set operations
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 diff(a, b) { | |
return _operation(a, b, [], diff, true) | |
} | |
function union(a, b) { | |
return _operation(a, b, b, union, true) | |
} | |
function intersect(a, b) { | |
return _operation(a, b, [], intersect) | |
} | |
function xor(a, b) { | |
return union(diff(a, b), diff(b, a)) | |
} | |
function equal(a, b) { | |
return !xor(a, b).length | |
} | |
function subset(a, b) { | |
return equal(intersect(a, b), a) | |
} | |
function membership(w, o) { | |
if (!o.length) return false | |
else return w == o[0] ? true : membership(w, o.slice(1)) | |
} | |
function _operation(a, b, r, f, p) { | |
if (!a.length) return r | |
else return membership(a[0], b) == !!p ? f(a.slice(1), b) : [a[0]].concat(f(a.slice(1), b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment