How to use memoize-one - 10 common examples

To help you get started, we’ve selected a few memoize-one 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 cruise-automation / webviz / packages / regl-worldview / src / commands / GLText.js View on Github external
|},
  },
|};

// Font size used in rendering the atlas. This is independent of the `scale` of the rendered text.
const FONT_SIZE = 40;
const BUFFER = 10;
const MAX_ATLAS_WIDTH = 512;
const SDF_RADIUS = 8;
const CUTOFF = 0.25;
const OUTLINE_CUTOFF = 0.6;

const BG_COLOR_LIGHT = Object.freeze({ r: 1, g: 1, b: 1, a: 1 });
const BG_COLOR_DARK = Object.freeze({ r: 0, g: 0, b: 0, a: 1 });

const memoizedCreateCanvas = memoizeOne((font) => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  ctx.font = font;
  return ctx;
});

// Build a single font atlas: a texture containing all characters and position/size data for each character.
const createMemoizedBuildAtlas = () =>
  memoizeOne(
    (charSet: Set): FontAtlas => {
      const tinySDF = new TinySDF(FONT_SIZE, BUFFER, SDF_RADIUS, CUTOFF, "sans-serif", "normal");
      const ctx = memoizedCreateCanvas(`${FONT_SIZE}px sans-serif`);

      let textureWidth = 0;
      const rowHeight = FONT_SIZE + 2 * BUFFER;
      const charInfo = {};
github kleros / doges-on-trial / src / sagas / notification.js View on Github external
import * as arbitrablePermissionListSelectors from '../reducers/arbitrable-permission-list'
import * as arbitrablePermissionListActions from '../actions/arbitrable-permission-list'
import * as dogeActions from '../actions/doge'
import { lessduxSaga } from '../utils/saga'
import { action } from '../utils/action'
import {
  web3,
  infuraArbitrablePermissionList,
  IMAGES_BASE_URL
} from '../bootstrap/dapp-api'
import * as dogeConstants from '../constants/doge'

import { fetchDoge } from './doge'

// Helpers
const getBlockDate = memoizeOne(blockHash =>
  web3.eth.getBlock(blockHash).then(block => new Date(block.timestamp * 1000))
)
const emitNotifications = async (account, timeToChallenge, emitter, events) => {
  const notifiedIDs = {}
  let oldestNonDisputedSubmittedStatusEvent

  for (const event of events.reverse()) {
    if (notifiedIDs[event.returnValues.value]) continue
    const isSubmitter = account === event.returnValues.submitter
    if (!isSubmitter || account !== event.returnValues.challenger) continue

    let message
    switch (Number(event.returnValues.status)) {
      case dogeConstants.IN_CONTRACT_STATUS_ENUM.Submitted:
        if (event.returnValues.disputed === true && isSubmitter)
          message = 'Your image has been challenged.'
github praneshr / react-diff-viewer / src / index.tsx View on Github external
import * as PropTypes from 'prop-types';
import cn from 'classnames';

import {
  computeLineInformation,
  LineInformation,
  DiffInformation,
  DiffType,
  DiffMethod,
} from './compute-lines';
import computeStyles, { ReactDiffViewerStylesOverride, ReactDiffViewerStyles } from './styles';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const m = require('memoize-one');

const memoize = m.default || m;

export enum LineNumberPrefix {
  LEFT = 'L',
  RIGHT = 'R',
}

export interface ReactDiffViewerProps {
  // Old value to compare.
  oldValue: string;
  // New value to compare.
  newValue: string;
  // Enable/Disable split view.
  splitView?: boolean;
  // Enable/Disable word diff.
  disableWordDiff?: boolean;
  // JsDiff text diff method from https://github.com/kpdecker/jsdiff/tree/v4.0.1#api
github Decathlon / react-table / src / components / utils / table.tsx View on Github external
import * as React from "react";
import { merge } from "lodash";
import * as memoize from "memoize-one";
import update from "immutability-helper";

import { DEFAULT_ROW_HEIGHT, MouseClickButtons } from "../constants";
import { IColumn, ITree, IColumns, ITrees } from "../table/elementary-table";
import { IRowOptions, IRow } from "../table/row";
import { ICell, ICellCoordinates } from "../table/cell";
import { Nullable } from "../typing";
import { isEmptyObj } from "./common";
import shallowEqual from "./shallowEqual";

// @ts-ignore https://github.com/s-yadav/react-number-format/issues/180
const memoizeFunc = memoize.default || memoize;

export enum ElevationType {
  start = "start",
  end = "end"
}

export interface IElevateds {
  [key: string]: ElevationType;
}

export interface IAbsoluteIndex {
  index: number;
  parentIndex: Nullable;
}

export interface IRelativeIndex {
github DonJayamanne / pythonVSCode / src / datascience-ui / interactive-common / variableExplorer.tsx View on Github external
this.state = { gridColumns: columns,
                       gridHeight: 200,
                       height: 0,
                       fontSize: 14,
                       sortColumn: 'name',
                       sortDirection: 'NONE'};

        this.divRef = React.createRef();

        // Memoize is different between the tests running and webpack. figure out which one
        // tslint:disable-next-line: no-any
        let memoize_func : any | undefined;
        if (memoize instanceof Function) {
            memoize_func = memoize;
        } else {
            memoize_func = memoize.default;
        }
        this.generateRows = memoize_func((variables: IJupyterVariable[], sortColumn: string | number, sortDirection: string): IGridRow[] => {
            const rows = !this.props.skipDefault ? this.generateDummyVariables() : this.parseVariables(variables);
            return this.internalSortRows(rows, sortColumn, sortDirection);
        });
    }
github material-components / material-components-web-react / packages / list / index.tsx View on Github external
private getListProps = (checkboxList?: boolean, radioList?: boolean) => ({
    checkboxList: Boolean(checkboxList),
    radioList: Boolean(radioList),
    handleKeyDown: this.handleKeyDown,
    handleClick: this.handleClick,
    handleFocus: this.handleFocus,
    handleBlur: this.handleBlur,
    onDestroy: this.onDestroy,
    getClassNamesFromList: this.getListItemClassNames,
    getListItemInitialTabIndex: this.getListItemInitialTabIndex,
  });

  // decreases rerenders
  // https://overreacted.io/writing-resilient-components/#dont-stop-the-data-flow-in-rendering
  getListPropsMemoized = memoizeOne(this.getListProps);

  render() {
    const {
      /* eslint-disable @typescript-eslint/no-unused-vars */
      className,
      checkboxList,
      radioList,
      nonInteractive,
      dense,
      avatarList,
      twoLine,
      singleSelection,
      role,
      selectedIndex,
      handleSelect,
      wrapFocus,
github Netflix / vector / src / app / components / Charts / Chart.jsx View on Github external
})
}

const verticalTickLineGenerator = (axisData) => {
  const { xy } = axisData
  const style = `M${xy.x1},${xy.y1}L${xy.x1},${xy.y2}Z`
  return
github kiwicom / margarita / packages / universal-components / src / RangeDatePicker / components / RenderMonth.js View on Github external
return true;
    return accumulator;
  }, false);
};

export default class RenderMonth extends React.Component {
  shouldComponentUpdate(nextProps: Props) {
    return (
      checkDatesForComponentUpdate(nextProps) ||
      checkDatesForComponentUpdate(this.props) ||
      this.props.isChoosingPastDatesEnabled !==
        nextProps.isChoosingPastDatesEnabled
    );
  }

  getWeeks = memoize((monthDate: MonthDateType) => {
    return getMonthMatrix(
      monthDate,
      this.props.weekStartsOn,
      (day, { isSameMonth }) => (isSameMonth ? new Date(day) : null),
    );
  }, isEqual);

  render() {
    const {
      monthDate,
      onDayPress,
      selectedDates,
      isRangePicker,
      weekStartsOn,
      isChoosingPastDatesEnabled,
      renderedCalendarRange,
github greenbone / gsa / gsa / src / web / components / chart / line.js View on Github external
: scaleLinear()
        .range([0, maxWidth(width)])
        .domain(xDomain);
});

const getYScale = memoize((data = [], height) => {
  const yValues = data.map(d => d.y);
  const yMax = Math.max(...yValues);
  const yDomain = data.length > 1 ? [0, yMax] : [0, yMax * 2];
  return scaleLinear()
    .range([maxHeight(height), 0])
    .domain(yDomain)
    .nice();
});

const getY2Scale = memoize((data = [], height) => {
  const y2Values = data.map(d => d.y2);
  const y2Max = Math.max(...y2Values);

  const y2Domain = data.length > 1 ? [0, y2Max] : [0, y2Max * 2];
  return scaleLinear()
    .range([maxHeight(height), 0])
    .domain(y2Domain)
    .nice();
});

export const lineDataPropType = PropTypes.shape({
  label: PropTypes.any.isRequired,
  color: PropTypes.toString.isRequired,
  width: PropTypes.number,
  dashArray: PropTypes.string,
});
github kiwicom / mobile / app / hotels / src / singleHotel / summary / RoomSummary.js View on Github external
import SummaryRow from './SummaryRow';
import type { RoomSummary_room as Room } from './__generated__/RoomSummary_room.graphql';
import SummaryButtons from './SummaryButtons';
import ExtraCharges from './ExtraCharges';

type Props = {|
  +room: ?Room,
  +goBack: () => void,
|};

type State = {|
  +isExpanded: boolean,
|};

const getSelectedRooms = memoize((props: Props) => {
  const availableRooms = props.room?.availableRooms ?? [];
  return availableRooms.filter(room => room?.selectedCount);
});

const getMaxNumberOfGuestsInSelection = memoize(selectedRooms => {
  return selectedRooms.reduce((acc, room) => {
    const selectedCount = room?.selectedCount ?? 0;
    const max = room?.maxOccupancy ?? 0;
    return acc + max * selectedCount;
  }, 0);
});

export class RoomSummary extends React.Component {
  state = {
    isExpanded: false,
  };

memoize-one

A memoization library which only remembers the latest invocation

MIT
Latest version published 3 years ago

Package Health Score

73 / 100
Full package analysis