michael@0: "use strict"; michael@0: michael@0: var method = require("../method/core") michael@0: michael@0: // Method is designed to work with data structures representing application michael@0: // state. Calling it with a state should return object representing `delta` michael@0: // that has being applied to a previous state to get to a current state. michael@0: // michael@0: // Example michael@0: // michael@0: // diff(state) // => { "item-id-1": { title: "some title" } "item-id-2": null } michael@0: var diff = method("diff@diffpatcher") michael@0: michael@0: // diff between `null` / `undefined` to any hash is a hash itself. michael@0: diff.define(null, function(from, to) { return to }) michael@0: diff.define(undefined, function(from, to) { return to }) michael@0: diff.define(Object, function(from, to) { michael@0: return calculate(from, to || {}) || {} michael@0: }) michael@0: michael@0: function calculate(from, to) { michael@0: var diff = {} michael@0: var changes = 0 michael@0: Object.keys(from).forEach(function(key) { michael@0: changes = changes + 1 michael@0: if (!(key in to) && from[key] != null) diff[key] = null michael@0: else changes = changes - 1 michael@0: }) michael@0: Object.keys(to).forEach(function(key) { michael@0: changes = changes + 1 michael@0: var previous = from[key] michael@0: var current = to[key] michael@0: if (previous === current) return (changes = changes - 1) michael@0: if (typeof(current) !== "object") return diff[key] = current michael@0: if (typeof(previous) !== "object") return diff[key] = current michael@0: var delta = calculate(previous, current) michael@0: if (delta) diff[key] = delta michael@0: else changes = changes - 1 michael@0: }) michael@0: return changes ? diff : null michael@0: } michael@0: michael@0: diff.calculate = calculate michael@0: michael@0: module.exports = diff