←back to thread

504 points azhenley | 1 comments | | HN request time: 0.356s | source
Show context
hackthemack ◴[] No.45771794[source]
One area that I like to have immutability is in function argument passing. In javascript (and many other languages), I find it weird that arguments in function act differently depending on if they are simple (strings, numbers) versus if they are complex (objects, arrays).

I want everything that passes through a function to be a copy unless I put in a symbol or keyword that it suppose to be passed by reference.

I made a little function to do deep copies but am still experimenting with it.

  function deepCopy(value) {
    if (typeof structuredClone === 'function') {
      try { return structuredClone(value); } catch (_) {}
    }
    try {
      return JSON.parse(JSON.stringify(value));
    } catch (_) {
      // Last fallback: return original (shallow)
      return value;
    }
  }
replies(3): >>45771864 #>>45772569 #>>45773187 #
1. jstimpfle ◴[] No.45771864[source]
Problem is that "copy" of an object is not well defined. It could be a "shallow" copy or a "deep" copy. The only models where "copy" is defined are simple "memory"/"value" models (like C) and immutable models (like Haskell).