Hacker News new | past | comments | ask | show | jobs | submit login

I'm not sure if you just want to complain about the naming, or are still genuinely looking for mnemonics. They may not be perfect, but that doesn’t mean they aren't helpful.

The direction is simple to remember: It’s the opposite from push/pop. I thought this wasn’t your issue. But there is another way to remember, in case you forget what direction push/pop is: Removing an item from the end of an array doesn’t require shifting (moving) the remaining elements (their indices remain the same). Removing an element from the front, however, requires shifting the elements (their indices do change). Therefore shift/unshift are the operations at the front of the array, and push/pop are the ones at the back.

The bookshelf analogy relies on "shift" being more common than "unshift" (otherwise the operations would have been named the other way around), and that shifting your books on a shelf is more common than the case where one book falls off the shelf and you have to put it back up ("unshift").

The reason using both shift and unshift is less common, as opposed to push and pop, is again due to efficiency considerations, since the latter don’t require shifting all elements. If you want to use the array as a LIFO stack, you use push and pop. If you want to use it as a FIFO queue, you use push and shift. Unshift is usually only used in more exceptional cases.




But you can do left shifts and right shifts. Your analogy works in comparison to right shifts, but it's backwards if compared to left shifts.


For the question of whether “shift” removes and “unshift” adds or vice versa, it doesn’t matter if it’s left or right shift. Yes, the bookshelf analogy doesn’t tell you at which end the removal or addition occurs. But as I said, I didn’t think this was the question being asked, and if it is being asked, then it can be answered with the index shifting and the comparison to push/pop.




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

Search: