Guest User

Untitled

a guest
Mar 13th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. // A LIST
  2.  
  3. const arrayToList = (arr) => {
  4. if (arr.length == 0) return;
  5. let val = arr.pop();
  6. return { value: val, rest: arrayToList(arr) }
  7. }
  8.  
  9. const listToArray = ({value, rest}, result = []) => {
  10. result.push(value);
  11. if (rest == null) return;
  12. listToArray(rest, result);
  13. return result;
  14. }
  15.  
  16. const prepend = (value, rest) => ({ value, rest });
  17.  
  18. const nth = ({value, rest}, position) => {
  19. if (position == 0) return value;
  20. return nth(rest, position - 1);
  21. }
  22.  
  23. console.log(arrayToList([10, 20]));
  24. // → {value: 10, rest: {value: 20, rest: null}}
  25. console.log(listToArray(arrayToList([10, 20, 30])));
  26. // → [10, 20, 30]
  27. console.log(prepend(10, prepend(20, null)));
  28. // → {value: 10, rest: {value: 20, rest: null}}
  29. console.log(nth(arrayToList([10, 20, 30]), 1));
  30. // → 20
  31.  
  32. // DEEP COMPARISON
  33.  
  34. const deepEqual = (a, b) => {
  35. if (a === b) return true;
  36.  
  37. if (a == null || typeof a != "object" ||
  38. b == null || typeof b != "object") return false;
  39.  
  40. const keysA = Object.keys(a), keysB = Object.keys(b);
  41.  
  42. if (keysA.length != keysB.length) return false;
  43.  
  44. for (let key of keysA) {
  45. if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
  46. }
  47.  
  48. return true;
  49. }
  50.  
  51. let obj = {here: {is: "an"}, object: 2};
  52. console.log(deepEqual(obj, obj));
  53. // → true
  54. console.log(deepEqual(obj, {here: 1, object: 2}));
  55. // → false
  56. console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
  57. // → true
Add Comment
Please, Sign In to add comment