Last active
August 29, 2015 14:19
-
-
Save lorenzoongithub/160d9e695508c578c22c to your computer and use it in GitHub Desktop.
equal.js
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
// | |
// A basic function to check whether two values are equal, in the intuitive sense. | |
// | |
function equal(a, b) { | |
if (a !== null && a !== undefined && b !== null && b !== undefined) { | |
if (a.length !== b.length) return false; | |
if (a !== a.toString() && b !== b.toString()) { | |
for (var i in a) { if (!equal(a[i],b[i])) return false; } | |
for (var i in b) { if (!equal(a[i],b[i])) return false; } | |
} | |
} | |
return (a+'') === (b+''); | |
} | |
// | |
// A basic function to check whether b is a subset of a.. | |
// | |
function subset(a, b) { | |
if (a !== null && a !== undefined && b !== null && b !== undefined) { | |
if (a.length !== b.length) return false; | |
if (b !== b.toString()) { | |
for (var i in b) { if (!equal(a[i],b[i])) return false; } | |
} | |
} | |
return (a+'') === (b+''); | |
} | |
// | |
// The use cases. | |
// | |
if (equal(124,124)) ; else throw ''; | |
if (equal(124,125)) throw ''; | |
if (equal('a','a')) ; else throw ''; | |
if (equal('a','b')) throw ''; | |
if (equal([],[])) ; else throw ''; | |
if (equal([],[1])) throw ''; | |
if (equal([1,2,3,4],[1,2,3])) throw ''; | |
if (equal([1,2,3],[1,2,3,4])) throw ''; | |
if (equal({a:1},{a:1})) ; else throw ''; | |
if (equal({a:1,b:1},{a:1})) throw ''; | |
if (equal({a:1,b:2,c:3,d:4},{a:1,c:3})) throw ''; | |
if (equal({a:1,b:1},{a:2})) throw ''; | |
if (equal(null,undefined)) throw ''; | |
if (equal(null,[])) throw ''; | |
if (equal(null,{})) throw ''; | |
if (equal(null,0)) throw ''; | |
if (equal(undefined,[])) throw ''; | |
if (equal(undefined,{})) throw ''; | |
if (equal(undefined,0)) throw ''; | |
if (equal({},[])) throw ''; | |
if (equal([],{})) throw ''; | |
if (equal([1],{0:1})) throw ''; | |
if (equal({0:1},[1])) throw ''; | |
if (equal('aaa',new String('aaa'))) ; else throw ''; | |
if (equal(123, new Number(123))) ; else throw ''; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment