javascript arrays can act like a fifo queue.
const fifo = [];
fifo.push(1)
fifo.push(2)
console.log(fifo.push(3)) // undefined
console.log(fifo) // [1, 2, 3]
const val = fifo.shift()
console.log(val, fifo) // 1, [2, 3]
However push, pop, unshift and shift all mutate the array. Here is an immutable way.
function immutablePush(arr, newEntry){
return [ ...arr, newEntry ]
}
function immutableShift(arr){
return arr.slice(1)
}
const fifo = [];
immutablePush(fifo, 1) // returns [1]
immutablePush(fifo, 2) // [1, 2]
immutablePush(fifo, 3) // [1, 2, 3]
const val = fifo[0] // 1
immutalbeShift(fifo) // returns [2, 3]
If you want to lookup data like you do in a object, you will need to normalize data.
In most cases you can simply use findIndex
const findByIdQueue(array, id) => {
const i = array.findIndex(item => item.id_queue === id);
// if i = -1 (not found) return undefined else return found item
return ~i ? undefined : array[i];
}
In react redux, we want to separate our access and update code. We access with selectors:
const selectFirstItem = state => {
// access state.fifo but set fifo to [] if state or state.fifo are undefined
const { fifo = [] } = state || {};
// return first array item or undefined if there is an empty list
return fifo[0];
}
const selectItemById = (state, ownProp) => {
const { fifo = [] } = state || {};
const { id } = ownProp || {};
return findByIdQueue(fifo, id);
}
const mapStateToProps = (state, ownProp) => ({
firstItem = selectFirstItem(state);
itemById = select(state, ownProp) // expect parent of MyCoolControl to pass in prop id
// <MyCoolControl id={24} />
})
export default connect(mapStateToProps)(MyCoolControl)
We update with actions:
const addItem = item => ({type: 'ADD_ITEM', item})
const removeFirstItem = () => ({type: 'REMOVE_FIRST_ITEM'})
const fifoReducer = (prev = defaultValue, action = {}) => {
const { type, item} = action;
switch (type) {
case "ADD_ITEM":
return [...prev, item];
case "REMOVE_FIRST_ITEM":
return prev.slice(1);
default: {
return prev;
}
}
};