Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

To me - it does, because using an index is always this fiddly thing. Do you increment/decrement the index before doing something or after? Do you need to check that you have incremented to len or above? Do you need to check that you haven't decremented below 0? You also can't truncate your undo history without also changing your pointer.

It really is better to have two separate arrays - unless your perf requirements dictate that you, for example, preallocate your entire stack and keep it fixed size.



I think it's nice to explore both approaches, but that an equally robust implementation can be made either way. Where yours might shine is if there is a lot of change in code directly accessing the data structures. The code directly accessing it could be constrained to being inside of the class using a private property, as I mentioned above. Logically you can think of it as two stacks while having a single array, and think of the stack pointer as splitting the stacks - and then you can go back and think about it in the more traditional way of an array with a stack pointer. I've written them both ways and it's helped me to understand the problem, but ultimately using a single array actually feels cleaner to me.


Fair point! It also felt clearer to me at first, but I found that I would need some "management" to avoid indexing into nonexistent indices and otherwise manage that pointer - like you are saying, the checks for that index not falling off the end/start of the stack would need to go somewhere. And I just wanted to have... _less stuff._ _Less stuff_ is better, certainly for me when doing solo dev.


I think I'll take another look at it. Maybe I'll prefer two stacks!

When I last implemented it, it was for an ambitious project, where I just got it working and then moved onto something else. The single stack seemed to work pretty well. https://codeberg.org/macchiato/ristretto/src/branch/window-w...

I used .at(), I'm not sure why, with a check to make sure it isn't under 0 at the right place, so the -1 behavior wasn't an issue. To see it working go to https://ristretto.codeberg.page/ on desktop and click client-server-simulator.md

Edit: I think it feels better to use at because it seems an accident of history that using an index doesn't error in JavaScript, while with at() it seems to be on purpose, like how .get() in python dicts doesn't error on a missing key.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: