-3

I'd like my objects to be immutable but copying the same object like hundred times doesn't make much sense to me.

const arr = [1,2,3]
const arr2 = [...arr, 4]
const arr3 = [...arr, 5]

What if I have to copy it more times? How can I deal with it? I don't wanna declare each time new const for an object for copying. How can I use it later in my program?

For example I've got a simple app that changes values in array and puts it into html.

const arr = [10,20];
foo(arr.map(x => x + 5))

What if I wanted to map it again with its new values? And then again and again? How would I deal with this problem?

Mark89
  • 7
  • 1
  • 6
    It is hard to know what your actual problem is. – epascarello Sep 09 '20 at 17:45
  • Make a single copy to a `let` declared variable, and reuse that variable every time you want to change the copy. Notice also, that `const` doesn't make the array immutable, it only makes the variable constant, i.e. you can do `arr[0] = 1000;`, but you can't do `arr = [1000, 2000, 3000];`. – Teemu Sep 09 '20 at 17:47
  • 1
    I think there is some confusion about FP here & whatever left is opinion based. The way to handle immutable data in FP depends on the exact case & sometimes on personal preferences. 99% of the time the answer is composition, sometimes it is lenses/prisms etc. but very rarely is it copying something a million times. If you find yourself doing this, something is wrong with your design & you should rethink your application's structure. Generally it would be a pipe of composed functions `f(..).map(..).filter(..).reduce(..)` if you need to execute side effects w/ an intermediate value you `tap` it – sinanspd Sep 09 '20 at 17:57
  • 1
    You are right, using native arrays in an immutable manner doesn't make much sense for big data. However, in frontend big data is rather rare. You can either use purely functional single linked lists or persistent arrays (immer.js, immutable.js) instead. Please also note that in FP state is stored in the call stack rather than with dozens of `const` declarations. –  Sep 09 '20 at 18:06
  • I'm sorry, but do you have an *actual* problem, i.e. you're having a specific performance issue that you've profiled? Or is this purely speculative? – Jared Smith Sep 09 '20 at 19:28

1 Answers1

-1

I don't wanna declare each time new const for an object for copying.

You can avoid writing const for every declaration using these strategies. There are probably more, depending on your exact use case.

const arr = [1, 2, 3];
const [arr2, arr3] = [[...arr, 4], [...arr, 5]];

console.log(arr2);
console.log(arr3);

const
  arr = [1, 2, 3],
  arr2 = [...arr, 4],
  arr3 = [...arr, 5];
 
console.log(arr2);
console.log(arr3);
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43