Created
January 12, 2017 01:39
-
-
Save dvdbng/b488bcc706765e81da87b9aa551c7f8f 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