Skip to content

Instantly share code, notes, and snippets.

@weepy
Created October 6, 2008 07:50
Show Gist options
  • Save weepy/15009 to your computer and use it in GitHub Desktop.
Save weepy/15009 to your computer and use it in GitHub Desktop.
// By weepy
function diff(b,a) {
var d={}
// additions
var tb = typeOf(b)
var ta = typeOf(a)
if(ta != tb)
return b
if(typeOf(b) == "number" || typeOf(a) == "string") {
if(b==a)
return undefined
else
return b
}
for(i in b ) {
var x = b[i]
var y = a[i]
var tx = typeOf(x)
var ty = typeOf(y)
if(x==y)
continue
if(tx == ty) {
if(tx=="number" || tx=="string") {
d[i] = x
} else {
var i = diff(x,y)
if(!is_empty(i))
d[i] = i
}
} else {
// changed types
d[i] = x
}
}
// removals
for(i in a) {
var x = b[i]
var y = a[i]
if(y && !x)
d[i] = null
}
if(is_empty(d))
return null
return d
}
function is_empty(obj) {
for(var i in obj)
return false
return true
}
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (typeof value.length === 'number' &&
!(value.propertyIsEnumerable('length')) &&
typeof value.splice === 'function') {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
//diff([1,2,3],[1,2,4]) => {2:3}
//diff([1,2,3],[1,2,3]) => null
//diff({a:1,b:2},{a:1}) => {b:2}
//diff({a:1},{a:2}) => {a:1}
//diff({a:1, b: {c:2,d:4} },{a:1 , b : {c:2} }) => { "[object Object]" => {d:4} }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment