Sha256: 4291b8d849ceb3e42b0471ee0c551142c9b5f67c1490e080e01d5062c361f91e

Contents?: true

Size: 1.37 KB

Versions: 5

Compression:

Stored size: 1.37 KB

Contents

"use strict";

var method = require("method")

// Method is designed to work with data structures representing application
// state. Calling it with a state should return object representing `delta`
// that has being applied to a previous state to get to a current state.
//
// Example
//
// diff(state) // => { "item-id-1": { title: "some title" } "item-id-2": null }
var diff = method("diff")

// diff between `null` / `undefined` to any hash is a hash itself.
diff.define(null, function(from, to) { return to })
diff.define(undefined, function(from, to) { return to })
diff.define(Object, function(from, to) {
  return calculate(from, to || {}) || {}
})

function calculate(from, to) {
  var diff = {}
  var changes = 0
  Object.keys(from).forEach(function(key) {
    changes = changes + 1
    if (!(key in to) && from[key] != null) diff[key] = null
    else changes = changes - 1
  })
  Object.keys(to).forEach(function(key) {
    changes = changes + 1
    var previous = from[key]
    var current = to[key]
    if (previous === current) return (changes = changes - 1)
    if (typeof(current) !== "object") return diff[key] = current
    if (typeof(previous) !== "object") return diff[key] = current
    var delta = calculate(previous, current)
    if (delta) diff[key] = delta
    else changes = changes - 1
  })
  return changes ? diff : null
}

diff.calculate = calculate

module.exports = diff

Version data entries

5 entries across 2 versions & 1 rubygems

Version Path
ruby-wisp-source-0.8.0 vendor/interactivate/node_modules/interactivate/node_modules/diffpatcher/diff.js
ruby-wisp-source-0.8.0 vendor/node_modules/wisp/interactivate/node_modules/interactivate/node_modules/diffpatcher/diff.js
ruby-wisp-source-0.7.0 vendor/interactivate/node_modules/interactivate/node_modules/diffpatcher/diff.js
ruby-wisp-source-0.7.0 vendor/node_modules/wisp/interactivate/node_modules/interactivate/node_modules/diffpatcher/diff.js
ruby-wisp-source-0.7.0 vendor/try/node_modules/~wisp/interactivate/node_modules/interactivate/node_modules/diffpatcher/diff.js