News for hackers. Stuff that matters.
Re:Writing a tiny undo/redo stack in JavaScript by balamatom on Wednesday March 26, 2025 @06:14PM (#43488057)
You can clear an array in JS by setting foo.length = 0? TIL.
Re:Writing a tiny undo/redo stack in JavaScript by dudus on Wednesday March 26, 2025 @08:16PM (#43489041)
I think this is actually the best way to zero an array in place. The other option is using foo.splice(0,foo.length)

foo = []; Will reassign the reference but other pointers can still have the array.

foo.length=1 will remove all elements but the first.

Re:Writing a tiny undo/redo stack in JavaScript by jansan on Thursday March 27, 2025 @02:34AM (#43490919)
foo.splice(0) is actually sufficient. From the docs:

"If deleteCount is omitted, or if its value is greater than or equal to the number of elements after the position specified by start, then all the elements from start to the end of the array will be deleted."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Re:Writing a tiny undo/redo stack in JavaScript by kupopuffs on Wednesday March 26, 2025 @06:54PM (#43488406)
omg this language just keeps getting deeper and deeper
Re:Writing a tiny undo/redo stack in JavaScript by z3t4 on Thursday March 27, 2025 @07:37AM (#43492534)
and just when you think you know it all it will get a major overhaul. Then there will come another language that compiles to JS, and then that language will die out and you have to rewrite your code into the next language that compiles to JS.
Re:Writing a tiny undo/redo stack in JavaScript by koito17 on Wednesday March 26, 2025 @10:24PM (#43489807)
That works because the length field acts as a fill pointer. In Common Lisp, it's also a common technique to empty an array in-place by setting the fill pointer to 0. The concept is quite old!

In most cases, there isn't a beneficial performance boost from emptying an array this way. One needs to allocate in a loop or do something equally inefficient to measure the difference between `coll = []` and `coll.length = 0`. (This assumes the language runtime does not statically allocate an immutable, empty array and use that to represent all empty arrays. Clojure does this, for instance, so no allocations occur when binding a variable to [] or other empty collections).

Re:Writing a tiny undo/redo stack in JavaScript by normie3000 on Thursday March 27, 2025 @01:04AM (#43490541)
> `coll = []` and `coll.length = 0`

In JavaScript these two statements have very different effects.

Re:Writing a tiny undo/redo stack in JavaScript by kazinator on Thursday March 27, 2025 @01:19AM (#43490583)
Adjusting the length of an array is a basic operation that should be in any language that has arrays/vectors.