How can I create a performant, immutable array in JavaScript? -


Say I have an array which is very much used, like an identity matrix, which I want to make sure that it has not been modified. By mistake. How can I create a JavaScript array that can not be modified?

Object.freeze Maybe what I want, but.

EDIT: Title is a requirement for specifying the display. We need to call a lot of WebGL calls! Edit <2> More: More specifically, this is for browser-based WebGL games (hence the need for performance), so whatever the features are Chrome and Firefox's current JavaScript Translators are in. Regarding the social pressure with the review of the code, of course! But we are still humans who make mistakes and sometimes write on the wrong variable.

You can set manually the mutation methods of the array:

 < Code> var mutatorMethods [['fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift']; Function preventMutation () {new type error ('array is irreversible'); } Function makeImmutableArray (origArray) {mutatorMethods.forEach (function (method) {origArray [method] = preventMutation;}); Return catalyst; } Var foo = makeImmutableArray (['foo', 'bar', 'baz']); As an example, refer to this JSN:  

However, glaze on only one major problem (considering one by direct indexing foo [0] = 'frozos'; ): Why do you need an irreversible array?

Repeat me, who do you want to stop modifying the array? If it is facing publicly, then I can say that you create your own object and expose the methods of the methods from which you expect them to be used. Adding a level of function calls to iterate is negligible for performance and this muttor prevents functions from highlighting.

Finally, if you are protecting the mutation by yourself, then your coding by hypersensitivity adds this complexity. Defensive coding is a better service for your interaction with the outside of the system (IMHO) against your own mistakes. Only makes code more complicated because you second guess that you will guess yourself and many times / or lack of continuity in a lot of investigation.

Instead, I like the concept of a moving object as an array object and by using it.

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -