All files / public/details/integrations state.ts

94.73% Statements 18/19
100% Branches 4/4
85.71% Functions 6/7
94.44% Lines 17/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50        2x         2x         2x   1x   2x   2x     24x 10x 6x     4x   8x 4x   8x 7x   8x         10x         2x      
import { atom, selector } from "recoil";
 
import type { IFilterChip, ISearchAndFilter } from "./types";
 
export const filterState = atom<IFilterChip[]>({
  key: "filterState",
  default: [],
});
 
export const filterChipsAtom = atom<ISearchAndFilter[]>({
  key: "filterChips",
  default: [],
});
 
export const filterChipsSelector = selector({
  key: "filterChipsSelector",
  get: ({ get }) => get(filterChipsAtom),
  set: ({ set, get }, newValue) => {
    const current = get(filterChipsAtom);
    // reduce newValue by id
    const newValues = (newValue as ISearchAndFilter[]).reduce(
      (acc, value) => {
        // Reduce on ID
        const match = acc.find((accItem) => accItem.id === value.id);
        if (!match) {
          acc.push(value);
        } else {
          // Reduce chips by value
          match.chips = [...match.chips, ...value.chips].reduce(
            (chipAcc, chipValue) => {
              const chipMatch = chipAcc.find(
                (chipAccItem) => chipAccItem.value === chipValue.value
              );
              if (!chipMatch) {
                chipAcc.push(chipValue);
              }
              return chipAcc;
            },
            [] as IFilterChip[]
          );
        }
        return acc;
      },
      current.map((item: ISearchAndFilter) => ({ ...item }))
    );
 
    set(filterChipsAtom, newValues);
  },
});