Level 3 – Advanced Implementation Flashcards

Focus: reimplementing JS internals, performance-aware patterns, non-trivial flows (10 cards)

1
Q

Implement a Polyfill for Object.create

Description
Your task is to write a function objectCreatePolyfill(proto) that creates a new object with its internal [[Prototype]] (i.e., __proto__) set to proto.

This replicates the behavior of the native Object.create.

⚙️ Requirements
* The returned object should inherit from proto
* Changes to the returned object should not affect proto
* The prototype chain should reflect proto as the direct parent

🧪 Example

const parent = { greeting: "hello" };
const child = objectCreatePolyfill(parent);

console.log(child.greeting); // → "hello"
console.log(Object.getPrototypeOf(child) === parent); // → true

🚫 Forbidden Patterns
You must NOT use:
* Object.create
* eval, Function, .toString
* __proto__ assignment
* Object.setPrototypeOf

Code

// objectCreatePolyfill.js

function objectCreatePolyfill(proto) {
  // TODO: return a new object with its prototype set to `proto`
}

🧪 Test Suite

// enforce-objectCreatePolyfill.js

(function enforceCreatePolyfillConstraints() {
  const src = objectCreatePolyfill.toString();
  const forbidden = [
    "Object.create",
    "eval", "Function", ".toString",
    "Object.setPrototypeOf",
    "\_\_proto\_\_"
  ];
  forbidden.forEach(term => {
    if (src.includes(term)) {
      throw new Error(`❌ Forbidden pattern used in objectCreatePolyfill(): "${term}" is not allowed.`);
    }
  });
})();

// test-objectCreatePolyfill.js

function runObjectCreatePolyfillTests() {
  const assert = (desc, actual, expected) => {
    const pass = actual === expected;
    console.log(`${pass ? "✅" : "❌"} ${desc}`);
    if (!pass) console.log(`   Expected: ${expected}, but got: ${actual}`);
  };

  const parent = { x: 42 };
  const child = objectCreatePolyfill(parent);

  assert("Child inherits property from parent", child.x, 42);
  assert("Prototype of child is parent", Object.getPrototypeOf(child), parent);

  child.x = 100;
  assert("Own property does not modify parent", parent.x, 42);

  const grandParent = { greet: () => "hi" };
  const parent2 = objectCreatePolyfill(grandParent);
  const child2 = objectCreatePolyfill(parent2);

  assert("Prototype chain supports multiple levels", child2.greet(), "hi");

  console.log("🎉 objectCreatePolyfill tests completed.");
}

runObjectCreatePolyfillTests();
A
function objectCreatePolyfill(proto) {
  function TempConstructor() {}
  TempConstructor.prototype = proto;
  return new TempConstructor();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Simulate JavaScript’s new Keyword

Description
Your task is to implement a function customNew(Constructor, …args) that mimics the behavior of the native new keyword in JavaScript.
When used like new Constructor(…args), the following happens:
1. A new empty object is created.
2. The prototype of that object is set to Constructor.prototype.
3. The Constructor is called with this set to the new object and passed the arguments.
4. If the Constructor returns an object, return that object; otherwise, return the newly created one.

🧪 Example

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const p1 = customNew(Person, "Alice", 30);
console.log(p1.name); // "Alice"
console.log(p1.age);  // 30
console.log(p1 instanceof Person); // true

🔒 Constraints
Disallow the use of the following patterns in your solution:
* eval
* Function constructor
* .toString
* Reflect.construct
* Native new keyword
These are restricted to encourage deep understanding and implementation of new behavior manually.

Code

// 🚧 Stubbed Implementation
function customNew(Constructor, ...args) {
  // TODO: Simulate the 'new' keyword behavior:
  // 1. Create empty object
  // 2. Set prototype
  // 3. Call constructor with new object as 'this'
  // 4. Return constructed object or fallback
}

🧪 Test Suite

// 🔒 Enforcement: Disallow forbidden patterns
(function enforceCustomNewConstraints() {
  const source = customNew?.toString?.() || "";
  const forbidden = ["eval", "Function", ".toString", "Reflect.construct", " new "];
  forbidden.forEach(term => {
    if (source.includes(term)) {
      throw new Error(`❌ Forbidden pattern used in customNew(): "${term}" is not allowed.`);
    }
  });
})();

function runCustomNewTests() {
  console.log("🔍 Running customNew Tests...");

  function Person(name, age) {
    this.name = name;
    this.age = age;
  }

  Person.prototype.sayHello = function() {
    return `Hi, I'm ${this.name}`;
  };

  const p = customNew(Person, "Bob", 25);

  console.assert(p.name === "Bob", "❌ Name should be 'Bob'");
  console.assert(p.age === 25, "❌ Age should be 25");
  console.assert(p.sayHello() === "Hi, I'm Bob", "❌ sayHello method failed");
  console.assert(p instanceof Person, "❌ Should be instance of Person");

  function Car(make) {
    this.make = make;
    return { type: "vehicle", brand: make }; // returns explicit object
  }

  const car = customNew(Car, "Tesla");
  console.assert(car.brand === "Tesla", "❌ Car brand should be Tesla");
  console.assert(car.type === "vehicle", "❌ Car type should be vehicle");

  console.log("✅ All customNew tests passed!");
}

// ✅ Run tests
runCustomNewTests();
A
function customNew(Constructor, ...args) {
  const obj = {};
  Object.setPrototypeOf(obj, Constructor.prototype);
  const result = Constructor.apply(obj, args);
  return result && (typeof result === "object" || typeof result === "function") ? result : obj;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Simulate the instanceof Operator

Description
Recreate the behavior of the JavaScript instanceof operator by implementing a function customInstanceOf(obj, Constructor).

🔍 Rules of instanceof
In JavaScript:
obj instanceof Constructor
evaluates to true if Constructor.prototype exists in the prototype chain of obj.

Your customInstanceOf(obj, Constructor) should follow the same logic.

💡 Example:

function Person(name) {
  this.name = name;
}
const bob = new Person("Bob");

console.log(customInstanceOf(bob, Person)); // true
console.log(customInstanceOf({}, Person));  // false
console.log(customInstanceOf(null, Person)); // false

Code

// 🚧 Stubbed Implementation
function customInstanceOf(obj, Constructor) {
  // TODO:
  // 1. Return false if obj is null or not an object
  // 2. Traverse the prototype chain of obj
  // 3. Check if any prototype === Constructor.prototype
}

🧪 Test Suite

// 🔒 Enforcement: Disallow forbidden patterns
(function enforceCustomInstanceOfConstraints() {
  const source = customInstanceOf?.toString?.() || "";
  const forbidden = ["eval", "Function", ".toString", "instanceof", "Reflect"];
  forbidden.forEach(term => {
    if (source.includes(term)) {
      throw new Error(`❌ Forbidden pattern used in customInstanceOf(): "${term}" is not allowed.`);
    }
  });
})();

function runCustomInstanceOfTests() {
  console.log("🧪 Running customInstanceOf Tests...");

  function Animal() {}
  function Dog() {}
  Dog.prototype = Object.create(Animal.prototype);
  Dog.prototype.constructor = Dog;

  const rover = new Dog();

  const tests = [
    { desc: "Dog instance is instance of Dog", actual: customInstanceOf(rover, Dog), expected: true },
    { desc: "Dog instance is instance of Animal", actual: customInstanceOf(rover, Animal), expected: true },
    { desc: "Plain object is not instance of Dog", actual: customInstanceOf({}, Dog), expected: false },
    { desc: "null is not instance of anything", actual: customInstanceOf(null, Dog), expected: false },
    { desc: "Object created with Object", actual: customInstanceOf({}, Object), expected: true },
    { desc: "Array is instance of Object", actual: customInstanceOf([], Object), expected: true },
    { desc: "Function is instance of Object", actual: customInstanceOf(() => {}, Object), expected: true },
  ];

  tests.forEach(({ desc, actual, expected }) => {
    if (actual === expected) {
      console.log(`✅ ${desc}`);
    } else {
      console.error(`❌ ${desc} — expected: ${expected}, got: ${actual}`);
    }
  });

  console.log("🎉 All tests completed");
}

// ✅ Run tests
runCustomInstanceOfTests();
A
function customInstanceOf(obj, Constructor) {
  if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) {
    return false;
  }

  let proto = Object.getPrototypeOf(obj);
  const targetProto = Constructor.prototype;

  while (proto) {
    if (proto === targetProto) return true;
    proto = Object.getPrototypeOf(proto);
  }

  return false;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Implement Promise.all

Recreate the behavior of the built-in Promise.all method.
Promise.all takes an iterable (usually an array) of promises (or values) and returns a new promise that:
* Resolves when all input promises resolve, with an array of their values in order.
* Rejects immediately when any input promise rejects, with the reason of the first rejection.
You must not use Promise.all internally.

🧪 Example

const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);

customPromiseAll([p1, p2, p3]).then(console.log); // [1, 2, 3]

If any promise rejects:

const p1 = Promise.resolve(1);
const p2 = Promise.reject("fail");
const p3 = Promise.resolve(3);

customPromiseAll([p1, p2, p3])
  .then(console.log)
  .catch(err => console.error(err)); // "fail"

🔒 Constraints
You must not use:
* Promise.all
* eval
* Function
* .toString
These are blocked to encourage building the full logic from scratch.

Code

// 🚧 Stubbed Implementation
function customPromiseAll(promises) {
  // TODO: Return a new promise that:
  // - resolves when all promises resolve
  // - rejects as soon as any promise rejects
}

🧪 Test Suite

// 🔒 Enforcement: Disallow forbidden patterns
(function enforceCustomPromiseAllConstraints() {
  const source = customPromiseAll?.toString?.() || "";
  const forbidden = ["Promise.all", "eval", "Function", ".toString"];
  forbidden.forEach(term => {
    if (source.includes(term)) {
      throw new Error(`❌ Forbidden pattern used in customPromiseAll(): "${term}" is not allowed.`);
    }
  });
})();

function runCustomPromiseAllTests() {
  console.log("🧪 Running customPromiseAll Tests...");

  const delay = (ms, val, shouldReject = false) =>
    new Promise((res, rej) =>
      setTimeout(() => (shouldReject ? rej(val) : res(val)), ms)
    );

  const assertResolved = async (desc, promises, expected) => {
    try {
      const result = await customPromiseAll(promises);
      const pass = JSON.stringify(result) === JSON.stringify(expected);
      console.log(`${pass ? "✅" : "❌"} ${desc}`);
      if (!pass) {
        console.log(`   Expected: ${expected}, got: ${result}`);
      }
    } catch (e) {
      console.log(`❌ ${desc} — Expected resolve but got rejection:`, e);
    }
  };

  const assertRejected = async (desc, promises, expectedError) => {
    try {
      await customPromiseAll(promises);
      console.log(`❌ ${desc} — Expected rejection but resolved`);
    } catch (e) {
      const pass = e === expectedError;
      console.log(`${pass ? "✅" : "❌"} ${desc}`);
      if (!pass) {
        console.log(`   Expected error: ${expectedError}, got: ${e}`);
      }
    }
  };

  Promise.resolve().then(async () => {
    await assertResolved("All promises resolve", [Promise.resolve(1), Promise.resolve(2)], [1, 2]);
    await assertResolved("Mixed promises and values", [1, Promise.resolve(2)], [1, 2]);
    await assertRejected("Immediate rejection short-circuits", [Promise.resolve(1), Promise.reject("boom"), Promise.resolve(3)], "boom");
    await assertResolved("Empty array resolves to empty", [], []);
    await assertRejected("Reject from delay", [delay(10, "ok"), delay(5, "fail", true)], "fail");

    console.log("🎉 customPromiseAll Tests Complete");
  });
}

runCustomPromiseAllTests();
A
function customPromiseAll(promises) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) return reject(new TypeError("Argument must be an array"));

    const results = [];
    let resolvedCount = 0;

    if (promises.length === 0) return resolve([]);

    promises.forEach((p, i) => {
      Promise.resolve(p)
        .then(value => {
          results[i] = value;
          resolvedCount++;
          if (resolvedCount === promises.length) {
            resolve(results);
          }
        })
        .catch(reject);
    });
  });
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Recreate Promise.race

Description
Recreate the behavior of the built-in Promise.race() method.
Promise.race() returns a promise that resolves or rejects as soon as one of the input promises settles, with that value or reason.

🔒 Constraints
You must not use:
* Promise.race
* eval, Function, .toString

💡 Examples
Success scenario:

const p1 = new Promise(resolve => setTimeout(() => resolve("first"), 100));
const p2 = new Promise(resolve => setTimeout(() => resolve("second"), 200));

customPromiseRace([p1, p2]).then(console.log); // "first"

Failure scenario:

const p1 = new Promise((_, reject) => setTimeout(() => reject("fail"), 50));
const p2 = new Promise(resolve => setTimeout(() => resolve("ok"), 100));

customPromiseRace([p1, p2])
  .then(console.log)
  .catch(err => console.error(err)); // "fail"
	```

**Code**

// 🚧 Stubbed Implementation
function customPromiseRace(promises) {
// TODO: Return a new promise that resolves/rejects
// as soon as the first promise settles
}
~~~

🧪 Test Suite

// 🔒 Enforcement: Disallow forbidden patterns
(function enforceCustomPromiseRaceConstraints() {
  const source = customPromiseRace?.toString?.() || "";
  const forbidden = ["Promise.race", "eval", "Function", ".toString"];
  forbidden.forEach(term => {
    if (source.includes(term)) {
      throw new Error(`❌ Forbidden pattern used in customPromiseRace(): "${term}" is not allowed.`);
    }
  });
})();

function runCustomPromiseRaceTests() {
  console.log("🧪 Running customPromiseRace Tests...");

  const delay = (ms, value, shouldReject = false) =>
    new Promise((res, rej) =>
      setTimeout(() => (shouldReject ? rej(value) : res(value)), ms)
    );

  const assertResolves = async (desc, promises, expected) => {
    try {
      const result = await customPromiseRace(promises);
      const pass = result === expected;
      console.log(`${pass ? "✅" : "❌"} ${desc}`);
      if (!pass) {
        console.log(`   Expected: ${expected}, but got: ${result}`);
      }
    } catch (e) {
      console.log(`❌ ${desc} — Expected resolve but got rejection:`, e);
    }
  };

  const assertRejects = async (desc, promises, expectedReason) => {
    try {
      await customPromiseRace(promises);
      console.log(`❌ ${desc} — Expected rejection but resolved`);
    } catch (e) {
      const pass = e === expectedReason;
      console.log(`${pass ? "✅" : "❌"} ${desc}`);
      if (!pass) {
        console.log(`   Expected error: ${expectedReason}, got: ${e}`);
      }
    }
  };

  Promise.resolve().then(async () => {
    await assertResolves("Resolves with first to resolve", [
      delay(100, "slow"),
      delay(50, "fast")
    ], "fast");

    await assertRejects("Rejects if first settles is rejection", [
      delay(30, "boom", true),
      delay(100, "slow")
    ], "boom");

    await assertResolves("Handles mixed values and promises", [
      "immediate",
      delay(10, "later")
    ], "immediate");

    await assertRejects("Immediate rejection wins", [
      Promise.reject("instant fail"),
      delay(10, "later")
    ], "instant fail");

    console.log("🎉 customPromiseRace Tests Complete");
  });
}

runCustomPromiseRaceTests();
A
function customPromiseRace(promises) {
  return new Promise((resolve, reject) => {
    for (let p of promises) {
      Promise.resolve(p).then(resolve, reject);
    }
  });
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

**LRU (Least Recently Used) Cache **

Description
Implement an LRU (Least Recently Used) Cache data structure using JavaScript.
* The cache has a fixed capacity.
* When the cache exceeds the capacity, it evicts the least recently used key.
* It must support:
* get(key): Return the value if the key exists, else return -1.
* put(key, value): Insert/update the key-value pair, updating usage order.
* Accessing a key via get() or put() makes it the most recently used.

🔒 Constraints:
❌ Do NOT use:
* eval, Function, toString()
* Global variables (window, globalThis)
✅ You may use Map, arrays, and plain JavaScript.

Code

// 🧱 Stubbed Implementation
function LruCache(capacity) {
  // TODO: Initialize the LRU cache data structure

  this.get = function(key) {
    // TODO: Return value if present, else -1
  };

  this.put = function(key, value) {
    // TODO: Insert or update key, and manage eviction if needed
  };
}

✅ Test Suite

// 🔒 Enforce forbidden patterns
(function enforceLruConstraints() {
  const source = LruCache.toString();
  const forbidden = ["eval", "Function", ".toString", "window", "globalThis"];
  forbidden.forEach(term => {
    if (source.includes(term)) {
      throw new Error(`❌ Forbidden pattern used: "${term}" is not allowed.`);
    }
  });
})();

function runLruCacheTests() {
  const assert = (desc, actual, expected) => {
    const pass = actual === expected;
    console.log(`${pass ? "✅" : "❌"} ${desc}`);
    if (!pass) console.log(`   Expected: ${expected}, Got: ${actual}`);
  };

  const cache = new LruCache(2);
  cache.put(1, 1);         // cache: {1=1}
  cache.put(2, 2);         // cache: {1=1, 2=2}
  assert("Get 1", cache.get(1), 1); // cache: {2=2, 1=1}
  cache.put(3, 3);         // evicts key 2 → cache: {1=1, 3=3}
  assert("Get 2 (evicted)", cache.get(2), -1);
  cache.put(4, 4);         // evicts key 1 → cache: {3=3, 4=4}
  assert("Get 1 (evicted)", cache.get(1), -1);
  assert("Get 3", cache.get(3), 3);
  assert("Get 4", cache.get(4), 4);

  console.log("🎉 All LRU cache tests completed.");
}

runLruCacheTests();
A
function LruCache(capacity) {
  this.cache = new Map();
  this.capacity = capacity;

  this.get = function(key) {
    if (!this.cache.has(key)) return -1;
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, value); // move to end (most recently used)
    return value;
  };

  this.put = function(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    }
    this.cache.set(key, value);
    if (this.cache.size > this.capacity) {
      // evict least recently used (first item)
      const lruKey = this.cache.keys().next().value;
      this.cache.delete(lruKey);
    }
  };
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Implement Array.prototype.flat

Description
Implement your own version of Array.prototype.flat as Array.prototype.myFlat.

Requirements:
* Accepts a single argument depth (default is 1) — the number of levels to flatten the array.
* Recursively flattens the nested array up to the specified depth.
* Must not mutate the original array.
* Must return a new, flattened array.

🔒 Constraints
Your solution must not use any of the following:
* eval
* Function constructor
* .toString()
* flat() or flatMap()
* Global variables like window or globalThis

Code

// 🧱 Stubbed Implementation
Array.prototype.myFlat = function(depth = 1) {
  // TODO: Implement recursive flattening logic
  // Return a new array, without mutating the original
};
// 🔒 Enforce Forbidden Patterns
(function enforceFlatConstraints() {
  const source = Array.prototype.myFlat?.toString?.();
  const forbidden = ["eval", "Function", ".toString", "window", "globalThis", ".flat", ".flatMap"];
  forbidden.forEach(term => {
    if (source?.includes(term)) {
      throw new Error(`❌ Forbidden pattern used in myFlat: "${term}"`);
    }
  });
})();
function runMyFlatTests() {
  const assertDeepEqual = (desc, actual, expected) => {
    const pass = JSON.stringify(actual) === JSON.stringify(expected);
    console.log(`${pass ? "✅" : "❌"} ${desc}`);
    if (!pass) {
      console.log(`   Expected: ${JSON.stringify(expected)}, but got: ${JSON.stringify(actual)}`);
    }
  };

  const arr1 = [1, 2, [3, 4]];
  assertDeepEqual("Flat depth 1", arr1.myFlat(), [1, 2, 3, 4]);

  const arr2 = [1, [2, [3, [4]]]];
  assertDeepEqual("Flat depth 2", arr2.myFlat(2), [1, 2, 3, [4]]);
  assertDeepEqual("Flat depth Infinity", arr2.myFlat(Infinity), [1, 2, 3, 4]);

  const arr3 = [1, [2, [3, [4, [5]]]]];
  assertDeepEqual("Flat depth 0 (no flattening)", arr3.myFlat(0), arr3);
  assertDeepEqual("Flat depth 3", arr3.myFlat(3), [1, 2, 3, 4, [5]]);

  const arr4 = [1, [2, [3, [4, [5]]]]];
  const flattened = arr4.myFlat(2);
  assertDeepEqual("Original array not mutated", arr4, [1, [2, [3, [4, [5]]]]]);

  console.log("🎉 All myFlat() tests completed.");
}

runMyFlatTests();
A
Array.prototype.myFlat = function(depth = 1) {
  const result = [];

  const flatten = (arr, level) => {
    for (const item of arr) {
      if (Array.isArray(item) && level > 0) {
        flatten(item, level - 1);
      } else {
        result.push(item);
      }
    }
  };

  flatten(this, depth);
  return result;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Priority Task Queue

Description
Implement a priority-based async task queue. The queue should:
* Accept tasks with a priority (lower number = higher priority)
* Always run the next highest priority task when possible
* Handle tasks that return promises (async)
* Only one task runs at a time

Code

function priorityTaskQueue() {
  // TODO: Return an object with `add(taskFn, priority)` method
}

🧪 Test Suite

(function enforce() {
  const src = priorityTaskQueue.toString();
  ["eval", "Function", "window", "globalThis"].forEach(forbidden => {
    if (src.includes(forbidden)) {
      throw new Error(`❌ Forbidden pattern used: ${forbidden}`);
    }
  });
})();

async function runPriorityQueueTests() {
  const results = [];
  const delay = ms => new Promise(res => setTimeout(res, ms));
  
  const queue = priorityTaskQueue();
  
  queue.add(async () => { await delay(50); results.push("A"); }, 2);
  queue.add(async () => { await delay(10); results.push("B"); }, 1);
  queue.add(async () => { results.push("C"); }, 3);

  await delay(200);

  console.assert(results.join("") === "BAC", "❌ Expected 'BAC', got " + results.join(""));
  console.log("✅ priorityTaskQueue passed");
}

runPriorityQueueTests();
A
function priorityTaskQueue() {
  const queue = [];
  let running = false;

  async function runNext() {
    if (running || queue.length === 0) return;
    running = true;

    // Sort by priority (asc)
    queue.sort((a, b) => a.priority - b.priority);
    const task = queue.shift();

    await task.fn();
    running = false;
    runNext();
  }

  return {
    add(fn, priority) {
      queue.push({ fn, priority });
      runNext();
    }
  };
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Observable

Description
Create an observable wrapper around an object that:
* Calls a subscriber callback every time a property changes
* Returns the original object
* Allows .subscribe(callback) and .unsubscribe(callback)

Code:

function createObservable(obj) {
  // TODO: Track changes and notify subscribers
}

🧪 Test Suite

(function enforce() {
  const src = createObservable.toString();
  ["eval", "Function", ".toString", "window", "globalThis"].forEach(fb => {
    if (src.includes(fb)) throw new Error(`❌ Forbidden: ${fb}`);
  });
})();

function runObservableTests() {
  const obj = { a: 1 };
  const observable = createObservable(obj);
  const changes = [];

  function listener(key, value) {
    changes.push(`${key}=${value}`);
  }

  observable.subscribe(listener);
  obj.a = 2;
  obj.b = 42;

  observable.unsubscribe(listener);
  obj.a = 3;

  console.assert(changes.join(",") === "a=2,b=42", `❌ Unexpected changes: ${changes.join(",")}`);
  console.log("✅ createObservable passed");
}

runObservableTests();
A
function createObservable(obj) {
  const listeners = new Set();

  const proxy = new Proxy(obj, {
    set(target, prop, value) {
      target[prop] = value;
      listeners.forEach(fn => fn(prop, value));
      return true;
    }
  });

  proxy.subscribe = fn => listeners.add(fn);
  proxy.unsubscribe = fn => listeners.delete(fn);

  return proxy;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

deepEqual

Description
Implement deepEqual(obj1, obj2) to recursively compare values. Handle:
* Arrays and objects
* Nested structures
* Primitives, null, and undefined
* Functions and Dates by reference equality

Code

function deepEqual(a, b) {
  // TODO: Deep recursive comparison
}

🧪 Test Suite

(function enforce() {
  const src = deepEqual.toString();
  ["eval", "Function", "window", "globalThis"].forEach(fb => {
    if (src.includes(fb)) throw new Error(`❌ Forbidden: ${fb}`);
  });
})();

function runDeepEqualTests() {
  console.assert(deepEqual(1, 1) === true, "❌ Numbers should match");
  console.assert(deepEqual({ a: 1 }, { a: 1 }) === true, "❌ Simple objects match");
  console.assert(deepEqual([1, [2]], [1, [2]]) === true, "❌ Nested arrays match");
  console.assert(deepEqual({ a: { b: 2 } }, { a: { b: 3 } }) === false, "❌ Should not match");
  console.assert(deepEqual(null, null) === true, "❌ Null check");
  console.assert(deepEqual(undefined, undefined) === true, "❌ Undefined check");

  const func = () => {};
  console.assert(deepEqual(func, func) === true, "❌ Function identity");
  console.assert(deepEqual(new Date(0), new Date(0)) === true, "❌ Dates equality");

  console.log("✅ deepEqual tests passed");
}

runDeepEqualTests();
A
function deepEqual(a, b) {
  if (a === b) return true;

  if (typeof a !== typeof b || a == null || b == null) return false;

  if (typeof a === "object") {
    if (Array.isArray(a) !== Array.isArray(b)) return false;

    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;

    return keysA.every(key => deepEqual(a[key], b[key]));
  }

  return false;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly