addon-sdk/source/lib/diffpatcher/diff.js

Sat, 03 Jan 2015 20:18:00 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Sat, 03 Jan 2015 20:18:00 +0100
branch
TOR_BUG_3246
changeset 7
129ffea94266
permissions
-rw-r--r--

Conditionally enable double key logic according to:
private browsing mode or privacy.thirdparty.isolate preference and
implement in GetCookieStringCommon and FindCookie where it counts...
With some reservations of how to convince FindCookie users to test
condition and pass a nullptr when disabling double key logic.

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

mercurial