Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. "use strict";
  2.  
  3. // JSON object comparizon without key order: o1 == o2
  4. function equals(o1, o2) {
  5. if (typeof o1 !== "object" || typeof o2 !== "object") return o1 === o2;
  6. if (o1 === null || o2 === null) return o1 === o2;
  7. if (Array.isArray(o1)) return Array.isArray(o2) &&
  8. o1.length === o2.length && o1.every((v, i) => equals(v, o2[i]));
  9. const k1 = Reflect.ownKeys(o1).sort(), k2 = Reflect.ownKeys(o2).sort();
  10. if (k1.length !== k2.length) return false;
  11. return k1.every((k, i) => k === k2[i] && equals(o1[k], o2[k]));
  12. }
  13.  
  14. // JSON satisfiability: o1 <= o2
  15. function satisfy(o1, o2) {
  16. if (typeof o1 !== "object" || typeof o2 !== "object") return o1 === o2;
  17. if (o1 === null || o2 === null) return o1 === o2;
  18. if (Array.isArray(o1)) return Array.isArray(o2) &&
  19. o1.every((v, i) => satisfy(v, o2[i]));
  20. const k1 = Reflect.ownKeys(o1), k2 = Reflect.ownKeys(o2);
  21. return k1.every(k => k2.includes(k) && satisfy(o1[k], o2[k]));
  22. }
  23.  
  24.  
  25. // case
  26. console.assert(equals(
  27. {foo: true, bar: {buzz: [1, 2, 3], quux: "abc"}},
  28. {bar: {quux: "abc", buzz: [1, 2, 3]}, foo: true}));
  29. console.assert(satisfy(
  30. {foo: true, bar: {buzz: [1, 2, 3], quux: "abc"}},
  31. {bar: {quux: "abc", buzz: [1, 2, 3, 4], $$: false}, foo: true, 1: null}));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement