How to use fast-memoize - 10 common examples

To help you get started, we’ve selected a few fast-memoize examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ozum / pg-structure / src / util / helper.ts View on Github external
const [tableAdjective, referencedTableAdjective] = getAdjectives(fk.name, fk.table.name, fk.referencedTable.name);

    return [
      tableAdjective ? `${tableAdjective}${fk.separator}${fk.table.name}` : fk.table.name,
      referencedTableAdjective ? `${referencedTableAdjective}${fk.separator}${fk.referencedTable.name}` : fk.referencedTable.name,
    ];
  },
  { serializer: memoizeSerializer }
);

// Memoize uses JSON.stringify to cache arguments. DB objects has circular data structures which cannot be serialized. Below are manually memoized functions:
/**
 * Memoized function to get foreign keys from source table to target table.
 * @hidden
 */
export const getForeignKeysTo = memoize((source: Table, target?: Table) => source.foreignKeys.filter(fk => fk.referencedTable === target), {
  serializer: memoizeSerializer,
});

/**
 * Creates a summary table in markdown format for all relations in database.
 *
 * @ignore
 * @param relationNameFunction is function to name relations.
 * @returns markdown table.
 *
 * @example
 * pgStructure({ database: "db", user: "user", password: "password" }).then(db => {
 *  console.log(getRelationsMarkdown(db));
 *  console.log(db.relationNameCollisions);
 * });
 */
github poooi / poi / views / utils / selectors.es View on Github external
!Array.isArray(landbaseEquipsId)
          ? undefined
          : effectiveEquips(
              zip(landbaseEquipsId, onslots).map(([equipId, onslot]) =>
                equipId <= 0
                  ? undefined
                  : modifiedEquipDataSelectorFactory(equipId)({ state, onslot }),
              ),
              slotnum,
            ),
    ),
  ),
)

// Return [map, $map] or undefined
export const mapDataSelectorFactory = memoize(mapId =>
  arrayResultWrapper(
    createSelector([mapsSelector, constSelector], (maps, { $maps }) => {
      if (!maps[mapId] || !$maps[mapId]) return
      return [maps[mapId], $maps[mapId]]
    }),
  ),
)

export const sortieMapIdSelector = createSelector(sortieSelector, sortie => sortie.sortieMapId)
export const sortieMapDataSelector = createSelector(
  [sortieMapIdSelector, mapsSelector, constSelector],
  (mapId, maps, { $maps }) => getMapData(mapId, maps, $maps),
)
export const sortieMapHpSelector = createSelector(sortieMapDataSelector, mapData =>
  mapData ? getMapHp(mapData[0], mapData[1]) : undefined,
)
github poooi / poi / views / utils / selectors.es View on Github external
],
    (fleet, { sortieStatus }) =>
      flatMap(sortieStatus, (sortie, index) => (sortie ? get(fleet, [index, 'api_ship'], []) : [])),
  ),
)

export const escapeStatusSelectorFactory = memoize(shipId =>
  createSelector(
    [sortieShipIdSelector, sortieSelector],
    (sortieShipIds, { escapedPos }) =>
      shipId > 0 && escapedPos.some(pos => sortieShipIds[pos] === shipId),
  ),
)

// There's a Number type check
const shipBaseDataSelectorFactory = memoize(shipId =>
  createSelector([shipsSelector], ships =>
    ships && typeof shipId === 'number' && shipId ? ships[shipId] : undefined,
  ),
)

// Reads props.shipId
// Returns [_ship, $ship]
// Returns undefined if uninitialized, or if ship not found in _ship
// Attention: shipId here only accepts Number type,
//   otherwise will always return undefined
export const shipDataSelectorFactory = memoize(shipId =>
  arrayResultWrapper(
    createSelector([shipBaseDataSelectorFactory(shipId), constSelector], (ship, { $ships }) =>
      $ships && typeof ship === 'object' && ship ? [ship, $ships[ship.api_ship_id]] : undefined,
    ),
  ),
github poooi / poi / views / utils / selectors.es View on Github external
),
)

const shipSlotnumSelectorFactory = memoize(shipId =>
  createSelector(shipBaseDataSelectorFactory(shipId), ship => (ship ? ship.api_slotnum : 0)),
)
const shipSlotSelectorFactory = memoize(shipId =>
  createSelector(shipBaseDataSelectorFactory(shipId), ship => (ship ? ship.api_slot : undefined)),
)
const shipExslotSelectorFactory = memoize(shipId =>
  createSelector(shipBaseDataSelectorFactory(shipId), ship => (ship ? ship.api_slot_ex : -1)),
)
const shipOnSlotSelectorFactory = memoize(shipId =>
  createSelector(shipBaseDataSelectorFactory(shipId), ship => (ship ? ship.api_onslot : undefined)),
)
const landbaseSlotnumSelectorFactory = memoize(landbaseId =>
  createSelector(landbaseSelectorFactory(landbaseId), landbase =>
    landbase ? landbase.api_plane_info.length : 0,
  ),
)
const landbaseOnSlotSelectorFactory = memoize(landbaseId =>
  createSelector(landbaseSelectorFactory(landbaseId), landbase =>
    landbase ? landbase.api_plane_info.map(l => l.api_count) : undefined,
  ),
)
// Returns [equipId for each slot on the ship]
// length is always 5 + 1(ex slot)
// Slot is padded with -1 for each empty slot
// Returns undefined if ship is undefined
const shipEquipsIdSelectorFactory = memoize(shipId =>
  arrayResultWrapper(
    createSelector(
github gnosis / dex-contracts / test / utilities.js View on Github external
return obj
}

/**
 * Given a sequence of index1, elements1, ..., indexN elementN this function returns
 * the corresponding MerkleTree of height 7.
 */
const _generateMerkleTree = function(...args) {
  const txs = Array(2 ** 7).fill(sha256(0x0))
  for (let i = 0; i < args.length; i += 2) {
    txs[args[i]] = args[i + 1]
  }
  return new MerkleTree(txs, sha256)
}
const generateMerkleTree = memoize(_generateMerkleTree, {
  strategy: memoize.strategies.variadic,
})

const sendTxAndGetReturnValue = async function(method, ...args) {
  const result = await method.call(...args)
  await method(...args)
  return result
}

/**
 * Partitions array into chunks of size spacing
 * @param input: Array
 * @param spacing: int
 * @returns {Array}
 */
function partitionArray(input, spacing) {
  const output = []
github helfi92 / material-ui-treeview / src / components / MuiTreeView / index.jsx View on Github external
if (searchRegExp.test(value)) {
        return true;
      }

      if (isLeaf) {
        return false;
      }

      const subtree = filter(node.nodes);

      return Boolean(subtree.length);
    });
  };

  const createFilteredTree = memoize(
    (tree, searchTerm) => (searchTerm ? filter(tree) : tree),
    {
      serializer: ([tree, searchTerm, softSearch]) =>
        `${JSON.stringify(tree)}-${searchTerm}-${softSearch}`,
    }
  );
  const renderNode = ({ node, parent, depth = 0, haltSearch }) => {
    const {
      searchTerm,
      softSearch,
      onLeafClick: _,
      onParentClick: __,
      expansionPanelSummaryProps,
      expansionPanelDetailsProps,
      listItemProps,
      caseSensitiveSearch,
github bokuweb / re-resizable / src / index.tsx View on Github external
if (size && typeof size === 'string') {
    if (endsWith(size, '%')) {
      const ratio = Number(size.replace('%', '')) / 100;
      return parentSize * ratio;
    } else if (endsWith(size, 'vw')) {
      const ratio = Number(size.replace('vw', '')) / 100;
      return window.innerWidth * ratio;
    } else if (endsWith(size, 'vh')) {
      const ratio = Number(size.replace('vh', '')) / 100;
      return window.innerHeight * ratio;
    }
  }
  return size;
};

const calculateNewMax = memoize(
  (
    parentSize: { width: number; height: number },
    maxWidth?: string | number,
    maxHeight?: string | number,
    minWidth?: string | number,
    minHeight?: string | number,
  ) => {
    maxWidth = getPixelSize(maxWidth, parentSize.width);
    maxHeight = getPixelSize(maxHeight, parentSize.height);
    minWidth = getPixelSize(minWidth, parentSize.width);
    minHeight = getPixelSize(minHeight, parentSize.height);
    return {
      maxWidth: typeof maxWidth === 'undefined' ? undefined : Number(maxWidth),
      maxHeight: typeof maxHeight === 'undefined' ? undefined : Number(maxHeight),
      minWidth: typeof minWidth === 'undefined' ? undefined : Number(minWidth),
      minHeight: typeof minHeight === 'undefined' ? undefined : Number(minHeight),
github taskcluster / taskcluster / ui / src / components / TaskGroupTable / index.jsx View on Github external
return mapping[sortBy];
};

const filterTasksByState = curry((filter, tasks) =>
  filter
    ? tasks.filter(({ node: { status: { state } } }) => filter.includes(state))
    : tasks
);
const filterTasksByName = curry((searchTerm, tasks) =>
  searchTerm
    ? tasks.filter(({ node: { metadata: { name } } }) =>
        lowerCase(name).includes(searchTerm)
      )
    : tasks
);
const createSortedTasks = memoize(
  (tasks, sortBy, sortDirection, filter, searchTerm) => {
    const filteredTasks = pipe(
      filterTasksByState(filter),
      filterTasksByName(searchTerm)
    )(tasks);

    if (!sortBy) {
      return filteredTasks;
    }

    return filteredTasks.sort((a, b) => {
      const firstElement =
        sortDirection === 'desc'
          ? valueFromNode(b.node, sortBy)
          : valueFromNode(a.node, sortBy);
      const secondElement =
github ember-intl / ember-intl / addon / -private / formatters / format-date.js View on Github external
constructor() {
    super();

    this.createNativeFormatter = memoize((locales, options) => {
      return new Intl.DateTimeFormat(locales, options);
    });
  }
github kaisermann / svelte-i18n / src / client / includes / formatters.ts View on Github external
locale = locale || getCurrentLocale()
  if (locale == null) {
    throw new Error('[svelte-i18n] A "locale" must be set to format numbers')
  }

  if (format) {
    options = getIntlFormatterOptions('number', format)
  }

  return new Intl.NumberFormat(locale, options)
})

export const getDateFormatter: MemoizedIntlFormatter<
  Intl.DateTimeFormat,
  Intl.DateTimeFormatOptions
> = memoize(({ locale, format, ...options } = {}) => {
  locale = locale || getCurrentLocale()
  if (locale == null) {
    throw new Error('[svelte-i18n] A "locale" must be set to format dates')
  }

  if (format) options = getIntlFormatterOptions('date', format)
  else if (Object.keys(options).length === 0) {
    options = getIntlFormatterOptions('date', 'short')
  }

  return new Intl.DateTimeFormat(locale, options)
})

export const getTimeFormatter: MemoizedIntlFormatter<
  Intl.DateTimeFormat,
  Intl.DateTimeFormatOptions

fast-memoize

Fastest memoization lib that supports N arguments

MIT
Latest version published 3 years ago

Package Health Score

70 / 100
Full package analysis

Popular fast-memoize functions