JSPM

  • Created
  • Published
  • Downloads 658978
  • Score
    100M100P100Q174792F
  • License MIT

Helpers function to get tree changes between two datasets

Package Exports

  • tree-changes

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (tree-changes) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

tree-changes

NPM version build status Maintainability Test Coverage

Get changes between two versions of the same object.
A good use for this is in React lifecycle methods, like componentWillReceiveProps or componentDidUpdate.

Setup

npm install tree-changes

Usage

import treeChanges from 'tree-changes';

const A = {
    status: 'idle',
    hasData: false,
    data: { a: 1 },
    items: [{ name: 'test' }],
    ratio: 0.45,
    retries: 0,
    switch: false,
};

const B = {
    status: 'done',
    hasData: true,
    data: { a: 1 },
    items: [],
    ratio: 0.4,
    retries: 1,
};

const { changed, changedFrom, changedTo, increased, decreased } = treeChanges(objA, objB);

if (changed('status')) {
    // do something
}

if (changedFrom('retries', 0, 1) {
    // do something else
}

if (decreased('ratio', true)) {
    // hey, slow down.
}

With React

import treeChanges from 'tree-changes';

class Comp extends React.Component {
    ...
    componentDidUpdate(prevProps) {
        const { changedFrom, changedTo } = treeChanges(prevProps, this.props);
        
        if (changedFrom('retries', 0, 1) {
            // dispatch some error
        }
        
        if (changedTo('hasData', true)) {
            // send data to analytics or something.
        }
    }
    ...
}

API

changed(key: string)
Check if the value has changed. Supports objects and arrays.

changedFrom(key: string, previous: string | boolean | number, actual: string | boolean | number)
Check if the value has changed from previous to actual.

changedTo(key: string, actual: string | boolean | number)
Check if the value has changed to actual.

increased(key: string)
Check if both versions are numbers and the value has increased.

decreased(key: string)
Check if both versions are numbers and the value has decreased.