Created
January 12, 2017 01:38
-
-
Save dvdbng/2649b6fabf3fb237f62515d499072b45 to your computer and use it in GitHub Desktop.
CoffeeScript deep object intersection
This file contains hidden or 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
intersection = (lst) -> | |
types = lst.map((x)-> typeof x) | |
if types.some((t) -> t != types[0]) | |
return null | |
switch types[0] | |
when "object" | |
res = {} | |
Object.keys(lst[0]).forEach (k) -> | |
if lst.every((o) -> k of o) | |
intersect = intersection lst.map((o) -> o[k]) | |
if intersect != null | |
res[k] = intersect | |
return res | |
when "number", "string", "boolean", "function" | |
if lst.some((e) -> e.toString() != lst[0].toString()) | |
return null | |
else | |
return lst[0] | |
else | |
throw new Error("unimplemented #{types[0]}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment