Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with an LRU and redux store strategy

I wanted to implement an LRU for a react-redux application, however I'm not sure what the best strategy of reading and writing data to the store via reducer so that I can maintain the LRU structure.

The goal is to implement an LRU for a most recent list of users. Effectively, whenever the application click on a specific contact, they get added to the most recent list of users. Let's say the list max out at 10 users, so effectively when it hit the max i'll pop off the oldest access user on the list.

I could associate a timestamp for each user in the list, but that means every time I read the state from the store, I would have to sort and find the oldest time stamp which i feel is slow.

I'm new to React/Redux, so please bear with me.

Any suggestions appreciated!

Thanks, Derek

like image 988
darewreck Avatar asked Dec 19 '25 22:12

darewreck


1 Answers

I would just have a seperate reducer that acts on the "select contact" action (there is probably another reducer that will also act on to set the currently selected user). It will maintain the array and just push to the front, and if the max is reachers, pop off the end.

Something like:

const initialState = []

export const lruReducer = (state = initialState, action) => {
    switch(action.type) {
        case 'SELECT_CONTACT':
            // copy the previous array (I'm assuming ES6 syntax here, but you could use Object.assign or ImmutableJS or something if preferred)
            // this is important to keep the state immutable
            let newState = [...state]

            // add the new contact (this is where you would do any de-duping logic
            newState.unshift(action.user) 

            // keep removing items until constraint is met
            while (newState.length > 10) {
                newState.pop()
            }

            // return new array
            return newState
        default:
            return state
    }
}

Then just combine this with your other reducers like normal.

like image 72
Michael Peyper Avatar answered Dec 22 '25 16:12

Michael Peyper