Skip to content

Instantly share code, notes, and snippets.

@electerious
Last active August 13, 2017 18:12
Show Gist options
  • Save electerious/ec6f21da54f1afc0e7b8f7ddb67ad5e5 to your computer and use it in GitHub Desktop.
Save electerious/ec6f21da54f1afc0e7b8f7ddb67ad5e5 to your computer and use it in GitHub Desktop.
Array with a max number of items
const fifo = (length) => {
const arr = []
return (value) => {
if (value===undefined) return arr
if (arr.length>=length) arr.shift()
arr.push(value)
return arr
}
}
@electerious
Copy link
Author

electerious commented Aug 12, 2017

Example:

const arr = fifo(4)

arr(0) // [ 0 ]
arr(1) // [ 0, 1 ]
arr(2) // [ 0, 1, 2 ]
arr(3) // [ 0, 1, 2, 3 ]
arr(4) // [ 1, 2, 3, 4 ]
arr(5) // [ 2, 3, 4, 5 ]
arr() // [ 2, 3, 4, 5 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment