Created
February 10, 2014 22:43
-
-
Save stevemadere/8925758 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!/usr/bin/env ruby | |
# hash_delta.rb | |
# script to demonstrate hash diff algorithm | |
# | |
require 'json' | |
old_state = { | |
n1: { | |
position: { x: 1, y: 2}, | |
}, | |
n2: { | |
position: { x: 3, y: 4}, | |
}, | |
} | |
new_state = { | |
n1: { | |
position: { x: 1, y: 2}, | |
}, | |
n2: { | |
position: { x: 3, y: 5}, | |
}, | |
n3: { | |
position: { x: 6, y: 7}, | |
}, | |
} | |
# javascript code for eql: | |
=begin | |
Object.prototype.eql = function (other) { | |
var x = this | |
var y = other | |
// if both are function | |
if (x instanceof Function) { | |
if (y instanceof Function) { | |
return x.toString() === y.toString(); | |
} | |
return false; | |
} | |
if (x === null || x === undefined || y === null || y === undefined) { return x === y; } | |
if (x === y || x.valueOf() === y.valueOf()) { return true; } | |
// if one of them is date, they must had equal valueOf | |
if (x instanceof Date) { return false; } | |
if (y instanceof Date) { return false; } | |
// if they are not function or strictly equal, they both need to be Objects | |
if (!(x instanceof Object)) { return false; } | |
if (!(y instanceof Object)) { return false; } | |
var p = Object.keys(x); | |
return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) ? | |
p.every(function (i) { return objectEquals(x[i], y[i]); }) : false; | |
} | |
=end | |
def find_difference(old_state,new_state) | |
diff = {} | |
new_state.keys.each do |key| | |
new_obj = new_state[key] | |
old_obj = old_state[key] | |
new_obj.keys.each do |property| | |
unless old_obj && old_obj[property].eql?(new_obj[property]) | |
diff[key] ||= {} | |
diff[key][property] = new_obj[property].clone | |
end | |
end | |
end | |
return diff | |
end | |
d = find_difference(old_state,new_state) | |
puts d.to_json | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment