npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jsondiffpatch-arrays-by-hash

v1.0.3

Published

A plugin for jsondiffpatch that supports tracking changes in arrays based on object hashes instead of indexes.

Downloads

2,548

Readme

jsondiffpatch-arrays-by-hash

A plugin for jsondiffpatch that supports tracking changes in arrays based on object hashes instead of indexes.

Why?

benjamine/jsondiffpatch is an awesome library for creating json patch objects from the difference between two JSON objects.

One nice feature is that it supports an objectHash function to better track items moving within an array. For example:

var withoutHash = jsondiffpatch.create();
var withHash = jsondiffpatch.create({objectHash: obj => obj.id});

var before = [{id: 1}, {id: 2}];
var after = [{id: 2}, {id: 1}];

// Without hash - Treated like objects didn't move, but their ids changed
withoutHash.diff(before, after);
// { '0': { id: [ 1, 2 ] }, '1': { id: [ 2, 1 ] }, _t: 'a' }

// With hash - Treated like a simple array re-order
with.diff(before, after);
// { _t: 'a', _1: [ '', 0, 3 ] }

This works within the context of one patch where the underlying JSON hasn't changed, but what if my underlying object changes or if I have multiple patches that I want to apply to the object? (like a merge)

var before = [{id: 1}, {id: 2}];
var flagged = [{id: 1}, {id: 2, foo: true}];

// Create two separate patches
// 1. Reorder patch just swaps objects 1 and 2 order
var reordered = [{id: 2}, {id: 1}];
var reorderPatch = withHash.diff(before, reordered);

// 2. Flag patch adds a property to object with ID 2
var flagged = [{id: 1}, {id: 2, foo: true}];
var flaggedPatch = withHash.diff(before, flagged);

// After some time passes, we apply the redorder patch
var after = withHash.patch(before, reorderPatch);

// And then apply the flagged patch, essentially doing a merge
after = withHash.patch(after, flaggedPatch);

// Oh no! The flag was instead applied to object with id 1, instead of 2
// [{id: 2}, {id: 1, foo: true}]

This plugin attempts to fix this shortcoming, by storing the result of objectHash with each array change, and then reapplying those changes to the element with the specified object hash instead of the specified array index.

Array Delta JSON Representation

You can see the default jsondiffpatch array delta format here.

In our version, we update the keys with some prefixes that have special meaning:

  • - - An array element was removed or moved
  • + - An array element was added
  • ! - An array element was modified
  • @ - The array key is an array index
  • # - The array key is an object hash

In practice deltas look liks this:

{
  _t: 'a',
  '+@4': [ { id: 'red' } ], // red item added at index 4
  '-#blue': [ { id: 'blue' }, 6, 0, 0 ], // blue item removed from index 6
  '-#green': [ '', 9, 4, 3 ], // green item moved
  '!#green': { value: [1, 2] }, // green item also had its value changed
}

How to use

npm install -s jsondiffpatch-arrays-by-hash

Next set up your jsondiffpatch instance and add in the plugin filters:

import jsonDiffPatch from 'jsondiffpatch';
import jsondiffpatchArraysByHash from 'jsondiffpatch-arrays-by-hash';

const instance = jsonDiffPatch.create({
  // Define an object hash function
  objectHash: function getObjectHash(obj, index) {
    return obj.id;
  },
  // Setting matchByPosition as a fallback for when objectHash returns undefined can create smaller diffs
  matchByPosition: true,
});

// Replace the default array filter with our new array filter for the pipes we care about
instance.processor.pipes.diff
  .replace('arrays', jsondiffpatchArraysByHash.diffFilter);
instance.processor.pipes.patch
  .replace('arrays', jsondiffpatchArraysByHash.patchFilter)
  .replace('arraysCollectChildren', jsondiffpatchArraysByHash.collectChildrenPatchFilter);
instance.processor.pipes.reverse
  .replace('arrays', jsondiffpatchArraysByHash.reverseFilter)
  .replace('arraysCollectChildren', jsondiffpatchArraysByHash.collectChildrenReverseFilter);

That's it! Use your jsondiffpatch instance to diff(), patch(), unpatch(), etc.

Who's Using It?

This plugin was initially built to support Uber's internal experimentation platform. We created a peer review system for approving changes to experiments, and needed the ability to merge these changes together reliably.