gkz / prelude-ls

prelude.ls is a functionally oriented utility library - powerful and flexible, almost all of functions are curried. It is written in, and is the recommended base library for, http://livescript.net
http://preludels.com/
MIT License
424 stars 59 forks source link

Add deep copy function #41

Open gkz opened 11 years ago

gkz commented 11 years ago

create a deep copy of objects/arrays

gkz/LiveScript#224

joneshf commented 11 years ago

How would this go? Do you need a deep-copy in both List and Obj, or should there one in index. Reason being, you could have a list with an object, or an object with a list. Both of which should be deep-copy-ed. So it seems like you'd have the exact same function in both, something like:

deep-copy = ->
  match typeof! it
  | (is \Object) => {[k, deep-copy v] for k, v of it}
  | (is \Array)  => [deep-copy i for i in it]
  | otherwise    => it

Are there other types I'm forgetting?

anko commented 10 years ago

@joneshf Cycles kill it:

a = {}
a.a = a     # self-reference
deep-copy a #=> [ infinite loop ]

Well, without tail-call optimisation, it'll overflow the stack instead.

Deep copy functions have been discussed extensively before and found hard or impossible.