I would assign to lastOperation only just before it will be used. Both mini-runtime optimization, but also helps to get the logic flaw, at least for me (surprised to see that lastOperations[lastOperations.length - 1] was already tried before lastOperations.length === 0 was checked.