diff.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. var method = require("../method/core")
  3. // Method is designed to work with data structures representing application
  4. // state. Calling it with a state should return object representing `delta`
  5. // that has being applied to a previous state to get to a current state.
  6. //
  7. // Example
  8. //
  9. // diff(state) // => { "item-id-1": { title: "some title" } "item-id-2": null }
  10. var diff = method("diff@diffpatcher")
  11. // diff between `null` / `undefined` to any hash is a hash itself.
  12. diff.define(null, function(from, to) { return to })
  13. diff.define(undefined, function(from, to) { return to })
  14. diff.define(Object, function(from, to) {
  15. return calculate(from, to || {}) || {}
  16. })
  17. function calculate(from, to) {
  18. var diff = {}
  19. var changes = 0
  20. Object.keys(from).forEach(function(key) {
  21. changes = changes + 1
  22. if (!(key in to) && from[key] != null) diff[key] = null
  23. else changes = changes - 1
  24. })
  25. Object.keys(to).forEach(function(key) {
  26. changes = changes + 1
  27. var previous = from[key]
  28. var current = to[key]
  29. if (previous === current) return (changes = changes - 1)
  30. if (typeof(current) !== "object") return diff[key] = current
  31. if (typeof(previous) !== "object") return diff[key] = current
  32. var delta = calculate(previous, current)
  33. if (delta) diff[key] = delta
  34. else changes = changes - 1
  35. })
  36. return changes ? diff : null
  37. }
  38. diff.calculate = calculate
  39. module.exports = diff