How can I create an executable, immutable array in JavaScript?

Let's say I have an array that used a lot, for example, the identity matrix, which I want to make sure that it is no coincidence. How to create a JavaScript array that cannot be changed?

Object.freezeI probably want, but jsperf reports that it is much slower than a regular array .

EDIT: A requirement is required to indicate performance. We have many WebGL challenges to make!

EDIT 2: In particular, this applies to the WebGL browser game (hence the performance requirement), so any functions are available in the current browser interpreters of Chrome and Firefox. As for social pressure with code reviews, absolutely! But we are still people who make mistakes and sometimes write the wrong variable.

+4
source share
1 answer

You can manually set the array mutator methods:

var mutatorMethods = ['fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'];

function preventMutation() {
  throw new TypeError('Array is immutable');
}

function makeImmutableArray(origArray) {
  mutatorMethods.forEach(function(method) {
    origArray[method] = preventMutation;
  });

  return origArray;
}

var foo = makeImmutableArray(['foo', 'bar', 'baz']);

See this jsbin for an example: http://jsbin.com/zeser/1/edit

This, however, only glazes the bigger problem (given that you can still modify the array using direct indexing foo[0] = 'froboz';): why do you need an immutable array?

, ? , , , . , .

, , . . (IMHO) . , if/else.

, Array .

+4
source

Source: https://habr.com/ru/post/1537803/


All Articles