@reduxjs/toolkit#createSelector JavaScript Examples

The following examples show how to use @reduxjs/toolkit#createSelector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: selectors.js    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
selectTopicsUnderCategory = createSelector(
  selectDiscussionProvider,
  selectBlocks,
  state => state.topics.topicsInCategory,
  (provider, blocks, topicsInCategory) => (
    provider === DiscussionProvider.LEGACY
      ? category => topicsInCategory?.[category]
      : category => blocks[category]?.topics
  ),
)
Example #2
Source File: index.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
hasAnyHighlightedRecordInScope = createSelector(
  [allRecordsWithFilterResponseSelector],
  (items) => !!items.find(({
    passesFilters: {
      type,
      date,
      // inCollection,
      showCollectionOnly,
      isHighlighted,
      // showHighlightedOnly,
    },
  }) => type && date && showCollectionOnly && isHighlighted),
)
Example #3
Source File: selectors.js    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
selectCoursewareTopics = createSelector(
  selectDiscussionProvider,
  selectCategories,
  selectTopicCategoryMap,
  selectTopics,
  selectSequences,
  (provider, categoryIds, topicsInCategory, topics, sequences) => (
    provider === DiscussionProvider.LEGACY
      ? categoryIds.map(category => ({
        id: category,
        name: category,
        topics: topicsInCategory[category].map(id => topics[id]),
      }))
      : sequences.map(sequence => ({
        id: sequence.id,
        name: sequence.displayName,
        topics: sequence.topics.map(topicId => ({ id: topicId, name: topics[topicId].name })),
      }))
  ),
)
Example #4
Source File: index.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
recordsFilteredByAllButDateSelector = createSelector(
  [allRecordsWithFilterResponseSelector],
  (items) => items.filter(({
    passesFilters: {
      type,
      showCollectionOnly,
      showHighlightedOnly,
    },
  }) => type && showCollectionOnly && showHighlightedOnly),
)
Example #5
Source File: postsSlice.js    From tclone with MIT License 6 votes vote down vote up
selectUserPosts = createSelector(
    [selectAllPosts, (state, username) => username],
    (posts, username) =>
        posts.filter(
            post =>
                post.user.screen_name === username ||
                (post.retweeted_by && post.retweeted_by.screen_name === username)
        )
)
Example #6
Source File: index.js    From discovery-mobile-ui with MIT License 5 votes vote down vote up
providersSelector = createSelector(
  [resourcesSelector],
  (resources) => values(resources).filter((r) => r.type === 'Organization'),
)
Example #7
Source File: courseSlice.jsx    From ResoBin with MIT License 5 votes vote down vote up
selectCourseTitle = (code) =>
  createSelector(
    selectCourseListMinified,
    (courseListMinified) =>
      courseListMinified.find((course) => course.code === code)?.title ?? ''
  )
Example #8
Source File: index.js    From rtk-demo with MIT License 5 votes vote down vote up
stateSelector = createSelector(makeSelectLocale(), (locale) => ({
  locale,
}))
Example #9
Source File: selectors.js    From frontend-app-discussions with GNU Affero General Public License v3.0 5 votes vote down vote up
selectAllLearners = createSelector(
  state => state.learners.pages,
  pages => pages.flat(),
)
Example #10
Source File: postsSlice.js    From tclone with MIT License 5 votes vote down vote up
selectPostById = createSelector(
    [selectAllPosts, (state, postId) => postId],
    (posts, postId) => posts.find(post => post.id_str === postId)
)
Example #11
Source File: selectors.js    From frontend-app-discussions with GNU Affero General Public License v3.0 5 votes vote down vote up
selectorForUnitSubsection = createSelector(
  selectBlocks,
  blocks => key => blocks[blocks[key]?.parent],
)
Example #12
Source File: index.js    From discovery-mobile-ui with MIT License 5 votes vote down vote up
activeCollectionSelector = createSelector(
  [collectionsSelector, activeCollectionIdSelector],
  (collections, activeCollectionId) => collections[activeCollectionId],
)
Example #13
Source File: notifySlice.js    From tclone with MIT License 5 votes vote down vote up
selectUnread = createSelector([notifySelectors.selectAll], all =>
    all.filter(one => !one.read)
)
Example #14
Source File: index.js    From discovery-mobile-ui with MIT License 5 votes vote down vote up
patientSelector = createSelector(
  [resourcesSelector],
  (resources) => values(resources).find((r) => r.type === 'Patient'),
)
Example #15
Source File: selectors.js    From frontend-app-discussions with GNU Affero General Public License v3.0 5 votes vote down vote up
selectAllThreads = createSelector(
  [
    state => state.threads.pages,
    selectThreads,
  ],
  (pages, threads) => pages.flatMap(ids => mapIdsToThreads(ids, threads)),
)
Example #16
Source File: index.js    From discovery-mobile-ui with MIT License 4 votes vote down vote up
timelineIntervalsSelector = createSelector(
  [
    filteredRecordsSelector, timelineRangeSelector, activeCollectionSelector, resourcesSelector], // eslint-disable-line max-len
  (filteredItemsInDateRange, timelineRange, activeCollection, resources) => {
    const { records } = activeCollection;

    let intervals = [];
    let intervalLength = 0;
    let maxCount1SD = 0; // up to mean + 1 SD
    let maxCount2SD = 0; // up to mean + 2 SD
    let maxCount = 0; // beyond mean + 2 SD
    let recordCount1SD = 0;
    let recordCount2SD = 0;
    let recordCount2SDplus = 0;

    const { dateRangeStart: minDate, dateRangeEnd: maxDate } = timelineRange;
    // alternatively:
    // const minDate = filteredItemsInDateRange[0]?.timelineDate;
    // const maxDate = filteredItemsInDateRange[filteredItemsInDateRange.length - 1]?.timelineDate;

    if (minDate && maxDate && filteredItemsInDateRange.length) {
      const numDays = Math.max(differenceInDays(maxDate, minDate), 1);
      const intervalCount = Math.min(numDays, MAX_INTERVAL_COUNT); // cannot be 0

      const intervalMap = createIntervalMap(minDate, maxDate, intervalCount);
      const getNextIntervalForDate = generateNextIntervalFunc(intervalMap, intervalCount);

      filteredItemsInDateRange.forEach(({ id, timelineDate }) => {
        const currentInterval = getNextIntervalForDate(timelineDate);
        if (currentInterval) {
          currentInterval.items.push(id); // < mutates intervalMap
          if (currentInterval.items.length > maxCount) {
            maxCount = currentInterval.items.length;
          }
        } else {
          console.warn('no interval for date: ', timelineDate); // eslint-disable-line no-console
        }
      });
      intervals = intervalMap;

      intervalLength = numDays / intervalCount;
    }

    const intervalsWithItems = intervals.filter(({ items }) => items.length); // has items

    if (intervalsWithItems.length) {
      const itemCounts = intervalsWithItems.map(({ items }) => items.length);
      const totalItemCount = itemCounts.reduce((acc, count) => acc + count, 0);
      const meanCountPerInterval = totalItemCount / itemCounts.length;
      const sumOfSquaredDifferences = itemCounts
        .reduce((acc, count) => acc + ((count - meanCountPerInterval) ** 2), 0);

      const populationSD = (sumOfSquaredDifferences / itemCounts.length) ** 0.5;

      // inject z score, and markedItems -- mutates intervalMap:
      intervalsWithItems.forEach((interval) => {
        const cardinality = interval.items.length;
        // eslint-disable-next-line no-param-reassign
        interval.zScore = !populationSD ? 0 : (cardinality - meanCountPerInterval) / populationSD;
        // ^ mutates intervalMap
        if (interval.zScore <= 1 && cardinality > maxCount1SD) {
          maxCount1SD = cardinality;
          recordCount1SD += cardinality;
        } else if (interval.zScore <= 2 && cardinality > maxCount2SD) {
          maxCount2SD = cardinality;
          recordCount2SD += cardinality;
        } else if (interval.zScore > 2) {
          recordCount2SDplus += cardinality;
        }

        // temporary dictionary to group items by type:
        const markedItemsDictionaryByType = interval.items
          .filter((id) => records[id]?.highlight) // either MARKED or FOCUSED
          .reduce((acc, id) => {
            const { subType } = resources[id];
            const idsByType = acc[subType] ?? [];
            return {
              ...acc,
              [subType]: idsByType.concat(id),
            };
          }, {});

        // eslint-disable-next-line no-param-reassign
        interval.markedItems = Object.entries(markedItemsDictionaryByType)
          .sort(sortMarkedItemsBySubType) // keep cartouches in alphabetical order by subType label
          .map(([subType, items]) => ({
            subType,
            marked: items,
            focused: items.filter((id) => records[id]?.highlight === FOCUSED),
          }));

        // eslint-disable-next-line no-param-reassign
        interval.collectionItems = interval.items.filter((id) => records[id]?.saved);
      });
    }

    return {
      minDate,
      maxDate,
      intervalCount: intervals.length,
      intervals: intervals.filter(({ items }) => items.length),
      intervalLength,
      maxCount,
      maxCount1SD,
      maxCount2SD,
      recordCount: filteredItemsInDateRange.length,
      recordCount1SD,
      recordCount2SD,
      recordCount2SDplus,
    };
  },
)