How to use the memoize-one function in memoize-one

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 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,
  };
github creative-connections / Bodylight.js-Composer / src / reducers / widgets / reducers / toggles.js View on Github external
const type = WidgetType.TOGGLE

export default function (state = {}, action) {
  switch (action.type) {
    case ADD_WIDGET:
      return addWidget(state, action.payload, type)
    case RENAME_WIDGET:
      return renameWidget(state, action.payload, type)
    case REMOVE_WIDGET:
      return removeWidget(state, action.payload, type)
  }
  return state
}

export const get = memoize(getWidget)
export const getAll = state => state
export const getForDropdown = memoize(getWidgetsForDropdown)
github sghall / resonance / docs / src / pages / demos / charts / DonutChart1.js View on Github external
return Math.PI > (d.startAngle + (d.endAngle - d.startAngle))
}

const getPolylinePoints = (startAngle, endAngle) => {
  const arc = { startAngle, endAngle }
  const p0 = innerArcPath.centroid(arc)
  const p1 = outerArcPath.centroid(arc)
  const p2 = [
    mid(arc) ? p1[0] + (radius * 0.5) : p1[0] - (radius * 0.5),
    p1[1],
  ]

  return { p0, p1, p2 }
}

const memoizedPoints = memoizedOne(getPolylinePoints)

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - (min + 1))) + min
}

function getArcs() {
  const data = shuffle(mockData)
    .map(({ name }) => ({ name, value: getRandom(10, 100) }))

  return pieLayout(sortBy(data, (d) => d.name))
}

class Example extends PureComponent {
  state = {
    arcs: getArcs(),
  }
github GridProtectionAlliance / openHistorian / Source / Applications / openHistorian / openHistorian / Grafana / public / app / features / explore / ExploreToolbar.tsx View on Github external
isPaused={isPaused}
                  start={this.startLive}
                  pause={this.pauseLive}
                  resume={this.resumeLive}
                  stop={this.stopLive}
                />
              
            )}
          
        
      
    );
  }
}

const getModeOptionsMemoized = memoizeOne(
  (
    supportedModes: ExploreMode[],
    mode: ExploreMode
  ): [Array>, SelectableValue] => {
    const supportedModeOptions: Array> = [];
    let selectedModeOption = null;
    for (const supportedMode of supportedModes) {
      switch (supportedMode) {
        case ExploreMode.Metrics:
          const option1 = {
            value: ExploreMode.Metrics,
            label: ExploreMode.Metrics,
          };
          supportedModeOptions.push(option1);
          if (mode === ExploreMode.Metrics) {
            selectedModeOption = option1;
github facebook / react-devtools / plugins / Profiler / views / SnapshotRanked.js View on Github external
selectFiber: SelectOrInspectFiber,
  snapshot: Snapshot,
  width: number,
): ItemData => ({
  focusedNode: rankedData.nodes[focusedNodeIndex],
  focusedNodeIndex,
  inspectFiber,
  nodes: rankedData.nodes,
  maxValue: rankedData.maxValue,
  scaleX: scale(0, rankedData.nodes[focusedNodeIndex].value, 0, width),
  selectFiber,
  snapshot,
  width,
}));

const getNodeIndex = memoize((rankedData: RankedData, id: string | null): number => {
  if (id === null) {
    return 0;
  }
  const { nodes } = rankedData;
  for (let index = 0; index < nodes.length; index++) {
    if (nodes[index].id === id) {
      return index;
    }
  }
  return 0;
});

const convertSnapshotToChartData = (snapshot: Snapshot, showNativeNodes: boolean): RankedData => {
  let maxSelfDuration = 0;

  const nodes = snapshot.committedNodes

memoize-one

A memoization library which only remembers the latest invocation

MIT
Latest version published 2 years ago

Package Health Score

70 / 100
Full package analysis