Currently i preparing for the algorithm interviews in IT companies. During problem solving I have met very common problem: I need to store last N elements as cache to be possible to use it by the constant address. It must take constant memory.
Example how it should work.
const arr = []
//limit must be 2
arr.push(1)
//[1]
arr.push(2)
//[1,2]
arr.push(3)
//[2,3]
Of course it’s possible to create dedicated function to implement this. But I’m trying to find the most elegant way to do it.
P.S. It’s not important which data structure will be used.