Skip to content

Instantly share code, notes, and snippets.

@Qaaj

Qaaj/reselect.js

Created Sep 7, 2017
Embed
What would you like to do?
Reselect Playground
var createStructuredSelector = require('reselect').createStructuredSelector;
var createSelector = require('reselect').createSelector;
// Example of structured selector
const mySelectorA = (state) => state.first_user;
const mySelectorB = (state) => state.second_user;
const mySelectorC = (state) => state.second_user + state.first_user;
const structuredSelector = createStructuredSelector({
first_user_total: mySelectorA,
second_user_total: mySelectorB,
total: mySelectorC,
});
const result = structuredSelector({ first_user: 8, second_user: 4 });
console.log(result); // { first_user_total: 8, second_user_total: 4, total: 12 }
// Re-using selectors with dynamic props by VALUE
const shopItemsSelector = state => state.items;
const expensiveItemSelectorFactory = minValue => {
return createSelector(
shopItemsSelector,
items => items.filter(item => item.value > minValue)
);
};
const subtotalSelector = (min) => createSelector(
expensiveItemSelectorFactory(min),
(items) => {
console.log('with dynamic min: ' + min);
return { cool: items.reduce((acc, item) => acc + item.value, 0) }
}
);
const subHarcoded10 = createSelector(
expensiveItemSelectorFactory(5),
(items) => {
console.log('without dynamic min');
return { cool: items.reduce((acc, item) => acc + item.value, 0) }
}
);
let subDynamic10 = subtotalSelector(10);
let data = { items: [{ value: 20 }, { value: 30 }] };
subDynamic10(data);
subDynamic10(data);
subHarcoded10(data);
subHarcoded10(data);
const hash = {};
// Non-Reference Memoization
const getIt = (id) => {
if (hash[id]) return hash[id];
let func = subtotalSelector(id);
hash[id] = func;
return func;
}
let obj1 = { value: 10 };
let obj2 = { value: 15 };
getIt(20)(data);
getIt(20)(data);
getIt(25)(data);
getIt(25)(data);
// Re-using selectors with dynamic props by REFERENCCE
// By Reference Memoization
const getItObj = (o) => {
let obj = hash[o.value];
if (obj && obj.o === o) return obj.func;
let func = subtotalSelector(o.value);
hash[o.value] = {
func,
o,
};
return func;
}
getItObj(obj1)(data);
getItObj(obj2)(data);
getItObj(obj1)(data);
getItObj(obj2)(data);
let temp1 = obj2;
obj2 = { value: 13 };
getItObj(obj2)(data);
getItObj(obj2)(data);
obj2 = temp1;
getItObj(obj1)(data);
getItObj(obj2)(data);
/* console.log
with dynamic min: 10
without dynamic min
with dynamic min: 20
with dynamic min: 25
with dynamic min: 10
with dynamic min: 15
with dynamic min: 13
* */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.