Skip to content

Instantly share code, notes, and snippets.

@olange
Created May 13, 2016 18:12
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 olange/525de34f236a06ea1ad4d9f918f977cd to your computer and use it in GitHub Desktop.
Save olange/525de34f236a06ea1ad4d9f918f977cd to your computer and use it in GitHub Desktop.
Symmetric difference of two Sets in CoffeeScript
##
# Given two sets A and B, returns a triple with the set of elements
# in A only, in both and in B only.
#
symmetricDiff = (setA, setB) ->
[inAOnly, inBoth, inBOnly] = [new Set(), new Set(), new Set()]
setA.forEach (eid) ->
(if setB.has( eid) then inBoth else inAOnly).add eid
setB.forEach (eid) ->
inBOnly.add( eid) unless inBoth.has( eid)
[inAOnly, inBoth, inBOnly]
a = new Set [55, 44, 33, 22, 11]
b = new Set [55, 1, 2, 3]
[A, both, B] = symmetricDiff a, b
console.info A, both, B
# Console output:
# -> Set {44, 33, 22, 11} Set {55} Set {1, 2, 3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment