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?
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: However, glaze on only one major problem (considering one by direct indexing 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. Object.freeze Maybe what I want, but.
< 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:
foo [0] = 'frozos'; ): Why do you need an irreversible array?
Comments
Post a Comment