Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active August 29, 2015 14:17
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 jremmen/1b8d4f6e378f7d765e57 to your computer and use it in GitHub Desktop.
Save jremmen/1b8d4f6e378f7d765e57 to your computer and use it in GitHub Desktop.
js: recursive 2 set operations
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