Created
December 28, 2018 15:26
-
-
Save handleman/7360db39e5a4fb4762a62a3e8e4eee3a to your computer and use it in GitHub Desktop.
mathematical set implementation in javascript
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 Set(items) { | |
var set = {}; | |
for (var i = 0; i < items.length; i++) { | |
set[items[i]] = true; | |
} | |
return set; | |
} | |
function copyInto(s, copy) { | |
for (var item in s) { | |
if (s[item] === true) { | |
copy[item] = true; | |
} | |
} | |
} | |
function union(s1, s2) { | |
var u = {}; | |
copyInto(s1, u); | |
copyInto(s2, u); | |
return u; | |
} | |
function intersection(s1, s2) { | |
var i = {}; | |
for (var item in s1) { | |
if (s1[item] === true && s2[item] === true) { | |
i[item] = true; | |
} | |
} | |
return i; | |
} | |
function difference(s1, s2) { | |
var diff = {}; | |
copyInto(s1, diff); | |
for (var item in s2) { | |
if (s2[item] === true) { | |
delete diff[item]; | |
} | |
} | |
return diff; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment