Last active
August 29, 2015 14:25
-
-
Save plonk/5ff742b1c079089d3425 to your computer and use it in GitHub Desktop.
便利に使えそうなイコール関数
This file contains hidden or 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
function generic_equal(a, b) { | |
// 同じ own プロパティの集合を持っている | |
function object_equal(a, b) { | |
if (typeof(a) != 'object' || typeof(b) != 'object') | |
throw new Error('object'); | |
var aKeys = Object.keys(a); | |
var bKeys = Object.keys(b); | |
if (aKeys.length != bKeys.length) | |
return false; | |
aKeys.sort(); | |
var i; | |
for (i = 0; i < aKeys.length; i++) { | |
var key = aKeys[i]; | |
if (!b.hasOwnProperty(key)) | |
return false; | |
if (!generic_equal(a[key], b[key])) | |
return false; | |
} | |
return true; | |
} | |
// オブジェクト参照同一、プリミティブ同値。 | |
if (a === b) | |
return true; | |
if (typeof(a) != typeof(b)) | |
return false; | |
if (typeof(a) == 'object') | |
return object_equal(a, b); | |
else | |
return false; | |
} | |
console.assert( generic_equal( 1, 1 ) ); | |
console.assert( generic_equal( [1], [1] ) ); | |
console.assert( generic_equal( [1,2], [1,2] ) ); | |
console.assert( generic_equal( [[1]], [[1]] ) ); | |
console.assert( generic_equal( [[[]]], [[[]]] ) ); | |
console.assert( generic_equal( {a:1}, {a:1}) ); | |
console.assert( generic_equal( [{a:1}], [{a:1}] ) ); | |
console.assert( generic_equal( {a:1,b:2}, {b:2,a:1} ) ); | |
console.assert( !generic_equal(1, 2) ); | |
console.assert( !generic_equal(1, "1") ); | |
console.assert( !generic_equal(0, null) ); | |
console.assert( !generic_equal([1], [2]) ); | |
console.assert( !generic_equal([], [[]]) ); | |
console.assert( !generic_equal([{a:[1]}], [{a:[2]}]) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment