How to use immutability-helper - 10 common examples

To help you get started, we’ve selected a few immutability-helper 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 DefinitelyTyped / DefinitelyTyped / immutability-helper / immutability-helper-tests.ts View on Github external
}

namespace TestArrayUpdate {
  update([], {
    foo: {
      bar: { $set: 'baz' }
    }
  });
}

namespace TestExtend {
  update.extend('$command', (specValue, originalValue) => originalValue);
}

namespace TestNewContext {
  update.newContext().extend('$command', (specValue, originalValue) => originalValue);
  newContext().extend('$command', (specValue, originalValue) => originalValue);

  // This shouldn't compile, but we can't test negatives.
  // newContext().newContext();
}

namespace TestFromReactDocs {
  // These are copied from https://facebook.github.io/react/docs/update.html
  let initialArray = [1, 2, 3];
  let newArray = update(initialArray, { $push: [4] }); // => [1, 2, 3, 4]

  let collection = [1, 2, { a: [12, 17, 15] }];
  let newCollection = update(collection, { 2: { a: { $splice: [[1, 1, 13, 14]] } } });
  // => [1, 2, {a: [12, 13, 14, 15]}]

  let obj = { a: 5, b: 3 };
github alleyinteractive / simplechart / app / components / lib / PalettePicker / index.js View on Github external
pickerChange() {
    // debouncing messes with the function args, so get current color this way
    const newColor = `#${this.picker.state.color.hex}`;
    let paletteArray = this.state.data.map(({ current }) => current);
    paletteArray = update(paletteArray, {
      [this.state.selectedIdx]: { $set: newColor },
    });

    // If there are more colors in the default palette than there are data series,
    // splice new array into default palette so we don't lose any
    if (this.state.defaultPalette.length > paletteArray.length) {
      paletteArray = paletteArray.concat(update(this.state.defaultPalette, {
        $splice: [[0, paletteArray.length]],
      }));
    }

    this.props.dispatch(actionTrigger(
      RECEIVE_CHART_OPTIONS,
      { color: paletteArray },
      'PalettePicker'
    ));
github Azure / pcs-remote-monitoring-webui / src / components / pages / dashboard / panels / telemetry / telemetryChart.js View on Github external
import React, { Component } from 'react';
import update from 'immutability-helper';
import { Observable } from 'rxjs';
import 'tsiclient';

import { joinClasses } from 'utilities';

import './telemetryChart.css';
// TODO: find a way to import without the relative path
import '../../../../../../node_modules/tsiclient/tsiclient.css';

const maxDatums = 100; // Max telemetry messages for the telemetry graph

// Extend the immutability helper to include object autovivification
update.extend('$auto', (val, obj) => update(obj || {}, val));

/**
 *  A helper function containing the logic to convert a getTelemetry response
 *  object into the chart object structure.
 *
 * @param getCurrentTelemetry A function that returns an object of formatted telemetry messages
 * @param items An array of telemetry messages from the getTelemetry response object
 */
export const transformTelemetryResponse = getCurrentTelemetry => items =>
  Observable.from(items)
    .flatMap(({ data, deviceId, time }) =>
      Observable.from(Object.keys(data))
        .filter(metric => metric.indexOf('Unit') < 0)
        .map(metric => ({ metric, deviceId, time, data: data[metric] }))
    )
    .reduce(
github Automattic / wp-calypso / client / lib / cart-values / index.js View on Github external
/**
 * Internal dependencies
 */
import {
	hasRenewalItem,
	hasFreeTrial,
	hasProduct,
	hasDomainRegistration,
	hasPlan,
} from './cart-items';
import { isCredits, isDomainRedemption, whitelistAttributes } from 'lib/products-values';
import { detectWebPaymentMethod } from 'lib/web-payment';

// Auto-vivification from https://github.com/kolodny/immutability-helper#autovivification
extendImmutabilityHelper( '$auto', function( value, object ) {
	return object ? update( object, value ) : update( {}, value );
} );

const PAYMENT_METHODS = {
	alipay: 'WPCOM_Billing_Stripe_Source_Alipay',
	bancontact: 'WPCOM_Billing_Stripe_Source_Bancontact',
	'credit-card': 'WPCOM_Billing_MoneyPress_Paygate',
	ebanx: 'WPCOM_Billing_Ebanx',
	eps: 'WPCOM_Billing_Stripe_Source_Eps',
	giropay: 'WPCOM_Billing_Stripe_Source_Giropay',
	ideal: 'WPCOM_Billing_Stripe_Source_Ideal',
	netbanking: 'WPCOM_Billing_Dlocal_Redirect_India_Netbanking',
	paypal: 'WPCOM_Billing_PayPal_Express',
	p24: 'WPCOM_Billing_Stripe_Source_P24',
	'brazil-tef': 'WPCOM_Billing_Ebanx_Redirect_Brazil_Tef',
	wechat: 'WPCOM_Billing_Stripe_Source_Wechat',
github NERDDISCO / luminave / src / reducers / index.js View on Github external
return update(state, { controllers: { [controllerIndex]: { mapping: { [mappingIndex]: { active: { $set: active } } } } } })
    case constants.ADD_SCENE_TO_MIDI:
      return update(state, { controllers: { [controllerIndex]: { mapping: { [mappingIndex]: { scenes: { $push: [sceneId] } } } } } })
    case constants.ADD_SCENES_TO_MIDI: {
      // Get the current scenes to merge them with the new scenes
      const oldSceneIds = state.controllers[controllerIndex].mapping[mappingIndex].scenes

      // Only add scenes that are not part of the MIDI element yet
      const newSceneIds = sceneIds.filter(sceneId => !oldSceneIds.includes(sceneId))

      return update(state, { controllers: { [controllerIndex]: { mapping: { [mappingIndex]: { scenes: { $push: newSceneIds } } } } } })
    }

    case constants.REMOVE_SCENE_FROM_MIDI: {
      sceneIndex = state.controllers[controllerIndex].mapping[mappingIndex].scenes.indexOf(sceneId)
      return update(state, { controllers: { [controllerIndex]: { mapping: { [mappingIndex]: { scenes: { $splice: [[sceneIndex, 1]] } } } } } })
    }

    case constants.LEARN_MIDI:
      return update(state, { learning: { $set: mappingIndex } })
    case constants.REMOVE_MIDI:
      return update(state, { controllers: { $splice: [[controllerIndex, 1]] } })
    default:
      return state
  }
}
github NERDDISCO / luminave / src / reducers / index.js View on Github external
return state.map((fixture, i) => {

        // fixtureBatch contains properties for the fixture in state
        if (fixtureBatch[fixture.id] !== undefined) {
          return update(state[i], { properties: { $merge: fixtureBatch[fixture.id].properties } })
        } else {
          return state[i]
        }

      })
github bwsw / cloudstack-ui / src / app / resource-quotas / redux / resource-quotas-admin-form.reducer.ts View on Github external
export function resourceQuotasAdminFormReducer(
  state = initialState,
  action: resourceQuotasActions.Actions,
): ResourceQuotasAdminFormState {
  switch (action.type) {
    case resourceQuotasActions.ResourceQuotasActionTypes.UPDATE_ADMIN_FORM_FIELD: {
      const resourceType = action.payload.resourceType;

      return update(state, {
        form: {
          [resourceType]: {
            $merge: omit(action.payload, 'resourceType'),
          },
        },
      });
    }

    case resourceQuotasActions.ResourceQuotasActionTypes.UPDATE_ADMIN_FORM: {
      return {
        ...state,
        form: action.payload,
      };
    }

    case resourceQuotasActions.ResourceQuotasActionTypes.UPDATE_RESOURCE_QUOTAS_REQUEST: {
github react-dnd / react-dnd / examples_decorators_js / 04-sortable / cancel-on-drop-outside / src / example.jsx View on Github external
(id, atIndex) => {
      const { card, index } = findCard(id)
      setCards(
        update(cards, {
          $splice: [
            [index, 1],
            [atIndex, 0, card],
          ],
        }),
      )
    },
    [cards],
github aio-libs / aiohttp-demos / demos / graphql / ui / src / components / ChatMessages.js View on Github external
updateQuery: (
            previousResult: Object,
            {subscriptionData}: Object
          ): Object => {
            if (!subscriptionData.data) {
              return previousResult;
            }

            const messageToAdd = get(subscriptionData, 'data.messageAdded');

            const newResult = update(previousResult, {
              room: {
                messages: {
                  $push: [messageToAdd],
                },
              },
            });
            return newResult;
          },
        });
github ChristopherChudzicki / math3d-react / client / src / services / errors / reducer.js View on Github external
return (state = initialState, action) => {

    const { type, payload, name } = action

    switch (type) {

      case SET_ERROR: {
        const { id, property } = payload
        const { type: errorType, errorMsg } = payload.errorData

        return errorTypes.has(errorType)
          ? update(state, {
            [id]: { [property]: { $set: errorMsg } }
          } )
          : state
      }

      case UNSET_ERROR: {
        const { id, property } = payload
        const { type: errorType } = payload.errorData
        return errorTypes.has(errorType)
          ? update(state, {
            [id]: { $unset: [property] }
          } )
          : state
      }

      case CREATE_MATH_OBJECT: {

immutability-helper

mutate a copy of data without changing the original source

MIT
Latest version published 4 years ago

Package Health Score

74 / 100
Full package analysis