• Stars
    star
    170
  • Rank 215,778 (Top 5 %)
  • Language
    JavaScript
  • Created over 9 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A micro library for diffing and patching JSON objects using a compact diff format

ฮ” dffptch.js

A micro library for diffing and patching JSON objects using a compact diff format.

Why

If your JavaScript client is sending a lot of updates to your backend โ€“ as it might in a collaborative app, a real-time game or a continously saving app โ€“ transfering the entire changed JSON wastes a lot of bandwidth. dffptch.js makes sending only the changes in a compact format very easy.

Example

var rabbit = {
  name: 'Thumper',
  color: 'grey',
  age: 2,
  bestFriend: 'bambi',
  foodNotes: {
    grassHay: 'his primary food'
  } 
};
// We make some changes to our rabbit
var updatedRabbit = {
  name: 'Thumper', // Still the same name
  color: 'grey and white', // He is white as well
  age: 3, // He just turned three!
  // we delete `bestFriend` โ€“ Thumper has many friends and he likes them equally
  foodNotes: {
    grassHay: 'his primary food', // Grass hay is still solid food for a rabbit
    carrots: 'he likes them a lot' // He also likes carrots
  } 
};
var delta = diff(rabbit, updatedRabbit);
// Delta is now a compact diff representing 1 deletion, 2 modifications and 1
// nested added property. The diff format might look odd, but is actually very
// simple as explained below.
assert.deepEqual(delta,
                 {"d": ["1"],
                  "m": {"0": 3, "2": "grey and white"},
                  "r": {"3": {"a": {"carrots": "he likes them a lot"}}}
                 });

Features

  • What you expect โ€“ Handles all types of changes. Added, modified and deleted properties. Nested objects and arrays.
  • Compact one way diffs โ€“ No needless verbosity. Property names are shortened to single characters while still remaining unambiguous.
  • Performant โ€“ Sane choices of algorithms. For instance, when generating the delta the keys of the old and new object are sorted, and then all changes are found in a single pass over both objects at the same time.
  • Very small โ€“ Too many huge libraries claim to be lightweight! This one is not among them. By having a tight focus on its targeted use case and a carefull implementation dffptch.js is barely 600B minified. Gzipped it's only 420B.
  • Readable source code โ€“ Well commented and less than 50 sloc. UglifyJS2 takes care of almost all golfing.
  • Availability: Available both as a CommonJS module, a AMD module and a plain old global export.
  • Tested: The test suite covers every feature.

Compared to other diff & patch libraries

  • It is significantly smaller. Ten times smaller than some alternatives.
  • In common cases dffptch.js generates smaller diffs because it only patches one way and thus can shorten property name.
  • It doesn't handle complex array changes as well as others. See the section on limitations below.

Install

bower install dffptch

or

npm install dffptch

How the diff format works

The diff format is an object with up to four properties. a is an object representing added properties. Each key is the name of a property and each value is the value assigned to the property. m is a similar object but for modified properties and with shortened keys. d is an array with deleted properties as elements. r contains all changes to nested objects and arrays, it recursively contains the four properties as well for the nested object.

An example

{
  a: {foo: 'bar'}, // One added property
  m: {'3': 'hello'}, // One modified property
  d: ['5'], // One deleted property
  r: {'3': { ... }} Changes to one nested object
}

In m, d and r the property names are shortened to single characters. The algorithm works like this: The keys in the original object are sorted, giving each key a unique number. The number is converted to a character using JavaScripts String.fromCharCode with an offset so the first key is assigned to the char '1' (this avoids the characters '/' and '' that require escaping in JSON.

So for this object

{
  foo: 'bar',
  sample: 'object',
  an: 'example'
}

we'd get the sorted keys ['an', 'foo', 'sample'] and thus an whould be shortened to '1', foo to '2' and sample to 3. There are a lot of unicode characters so this approach is safe no matter how many properties your objects have.

Browser support

dffptch.js is environment independent (neither Node nor a browser is required). It does however use the two ECMAScript 5 functions Object.keys and Array.prototype.map. If you require support for < IE9 you should polyfill those functions (splendid polyfills are included in the MDN links above).

Limitations

The differences generated by dffptch.js can only take you from a to b. Not from b to a. This is by design and is necessary for the compact format.

dffptch.js handles arrays as it handles objects. Order is not taken into account. If you're changing elements or append to an array this is not an issue. However, if you're reordering or inserting elements the diffs will be suboptimal. Finding the shortest edit distance in an ordered and possibly nested collection whould complicate dffptch.js significantly with little benefit. Simply flattening your data before feeding it to dffptch.js avoids the problem.

License

dffptch.js is made by Simon Friis Vindum. But copyright declarations wastes bandwidth. thus dffptch.js is public domain or WTFPL or CC0. Do what you want but please follow me on Twitter or give a GitHub star if you feel like it.

More Repositories

1

flyd

The minimalistic but powerful, modular, functional reactive programming library in JavaScript.
JavaScript
1,566
star
2

functional-frontend-architecture

A functional frontend framework.
JavaScript
1,444
star
3

union-type

A small JavaScript library for defining and using union types.
JavaScript
475
star
4

synceddb

Makes it easy to write offline-first applications with realtime syncing and server side persistence.
JavaScript
397
star
5

composable.el

Composable text editing for Emacs.
Emacs Lisp
115
star
6

functionize

A library which aids in making any JavaScript library more functional.
JavaScript
49
star
7

projectdo

Context-aware single-letter project commands to speed up your terminal workflow.
Shell
47
star
8

Kran

An entity system written in JavaScript.
JavaScript
42
star
9

Gtk98Icons

An icon theme for GTK that looks like Windows 98
PHP
40
star
10

smart-comment

Smarter commenting for Emacs
Emacs Lisp
40
star
11

sync-promise

Compact synchronized promise implementation. Promises/A+ incompliant. Works inside IdexedDB transactions.
JavaScript
32
star
12

dot-compose

Function composition with dot as a composition operator.
JavaScript
23
star
13

seamless-fantasy

Make fantasy land seamlessly compatible with plain JavaScript data structures.
JavaScript
10
star
14

list-difference

Fast algorithm for finding edits between lists.
JavaScript
10
star
15

duck

๐Ÿฆ† Turns a TypeScript file into JSON describing the files exports.
TypeScript
8
star
16

find-the-function

A tiny tool for finding functions from libraries
TypeScript
7
star
17

ryter

A tiny JavaScript router
JavaScript
7
star
18

web-swipe-view

Horizontal swipe views for mobile web applications
JavaScript
7
star
19

finger-tree

Highly optimized implementation of finger trees in JavaScript
TypeScript
6
star
20

flyview

Efficient views powered by streams/ovservables/functional reactive properties.
JavaScript
6
star
21

fake-raf

A fake requestAnimationFrame perfect for unit testing.
JavaScript
5
star
22

flyd-forwardto

Create a new stream that passes all values through a function and forwards them to a target stream.
JavaScript
4
star
23

maxima-calculus2

Maxima funktioner til lรธsning af eksamensopgaver i kurset Calculus 2 pรฅ Aarhus Universitet
4
star
24

turing-patterns

Multi-Scale Turing Patterns
JavaScript
4
star
25

reflex-examples

A collection of examples using Reflex.
Haskell
3
star
26

flyd-scanmerge

Flyd module for conveniently merging and reducing several streams into one.
JavaScript
3
star
27

flyd-obj

Functions for working with stream in objects.
JavaScript
3
star
28

category-theory-notes

TeX
3
star
29

matmod

Handy functions for matMod written in R for Jupyter
Jupyter Notebook
3
star
30

dnd-scroll

Proper edge scroll when dragging with HTML 5 drag and drop!
JavaScript
3
star
31

dffptch-haskell

A small library for diffing and patching JSON objects using a compact diff format
Haskell
2
star
32

keyano-vscode

Next-generation keyboard-driven editing language. Edit code at the speed of light.
TypeScript
2
star
33

flyd-filter

Filter function for Flyd.
JavaScript
2
star
34

planetsimulator

A physical simulation of planetary motion written in JavaScript
JavaScript
2
star
35

flyd-every

Takes a time interval t and creates a stream of the current time updated every t.
JavaScript
1
star
36

paldepind.github.io

CSS
1
star
37

hareactive-old

Experimental WIP.
JavaScript
1
star
38

vdom-benchmark-snabbdom

Virtual DOM Benchmark implementation for Snabbdom library.
JavaScript
1
star
39

simple-frp

An attempt at creating a very simple FRP library for educational purposes.
TypeScript
1
star
40

flyd-sampleon

sampleOn for Flyd.
JavaScript
1
star
41

software-foundations

My solutions to exercises in Benjamin C. Pierce's Software Foundations
HTML
1
star
42

flyd-keepwhen

keepWhen function for Flyd.
JavaScript
1
star
43

flyd-lift

Lift function for Flyd.
JavaScript
1
star
44

dotfiles

Repository containing my dotfiles.
Emacs Lisp
1
star
45

react-native-chainable-stylesheet

TypeScript
1
star
46

flyd-aftersilence

Flyd module that buffers values from a stream and emits them after a specified duration of silience.
JavaScript
1
star
47

domain-theory

CSS
1
star