Created
November 22, 2016 22:56
-
-
Save arackaf/289d7ba664a6e5f54e01ab4d29cb5884 to your computer and use it in GitHub Desktop.
11-22-16-subjectsStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function rootReducer(state = initialState, action){ | |
switch(action.type){ | |
case LOAD_SUBJECTS: | |
return Object.assign({}, state, { subjectsInitialQueryFired: true }); | |
case LOAD_SUBJECTS_RESULTS: | |
return Object.assign({}, state, { subjectHash: subjectsToHash(action.subjects), subjectsLoaded: true }); | |
case LOAD_COLORS: | |
return Object.assign({}, state, { colors: action.colors }); | |
} | |
return state; | |
} | |
const subjectsToHash = subjects => subjects.reduce((hash, s) => (hash[s._id] = s, hash), {}); | |
const subjectSortCompare = ({ name: name1 }, { name: name2 }) => { | |
let name1After = name1.toLowerCase() > name2.toLowerCase(), | |
bothEqual = name1.toLowerCase() === name2.toLowerCase(); | |
return bothEqual ? 0 : (name1After ? 1 : -1); | |
}; | |
export const stackAndGetTopLevelSubjects = subjectsHash => { | |
let subjects = Object.keys(subjectsHash).map(_id => ({...subjectsHash[_id]})); | |
subjects.sort(subjectSortCompare).forEach(s => { | |
s.children = []; | |
s.children.push(...subjects.filter(sc => new RegExp(`,${s._id},$`).test(sc.path)).sort(subjectSortCompare)); | |
s.childLevel = !s.path ? 0 : (s.path.match(/\,/g) || []).length - 1; | |
}); | |
return subjects.filter(s => s.path == null); | |
} | |
export const subjectsSelector = createSelector([subjectHash => subjectHash], subjectHash => ({ | |
subjects: stackAndGetTopLevelSubjects(subjectHash) | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment