Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A LIST
- const arrayToList = (arr) => {
- if (arr.length == 0) return;
- let val = arr.pop();
- return { value: val, rest: arrayToList(arr) }
- }
- const listToArray = ({value, rest}, result = []) => {
- result.push(value);
- if (rest == null) return;
- listToArray(rest, result);
- return result;
- }
- const prepend = (value, rest) => ({ value, rest });
- const nth = ({value, rest}, position) => {
- if (position == 0) return value;
- return nth(rest, position - 1);
- }
- console.log(arrayToList([10, 20]));
- // → {value: 10, rest: {value: 20, rest: null}}
- console.log(listToArray(arrayToList([10, 20, 30])));
- // → [10, 20, 30]
- console.log(prepend(10, prepend(20, null)));
- // → {value: 10, rest: {value: 20, rest: null}}
- console.log(nth(arrayToList([10, 20, 30]), 1));
- // → 20
- // DEEP COMPARISON
- const deepEqual = (a, b) => {
- if (a === b) return true;
- if (a == null || typeof a != "object" ||
- b == null || typeof b != "object") return false;
- const keysA = Object.keys(a), keysB = Object.keys(b);
- if (keysA.length != keysB.length) return false;
- for (let key of keysA) {
- if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
- }
- return true;
- }
- let obj = {here: {is: "an"}, object: 2};
- console.log(deepEqual(obj, obj));
- // → true
- console.log(deepEqual(obj, {here: 1, object: 2}));
- // → false
- console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
- // → true
Add Comment
Please, Sign In to add comment