Katkat

Build a Chainable Rectangle Manipulation API

RobinhoodFrontend Engineer · Technical Screen

Last updated

This problem tests your ability to design a fluent interface (method chaining) that manages an internal queue of asynchronous operations to ensure tasks execute sequentially.

Problem Statement

Design a JavaScript class called RectChain that allows for declarative manipulation of a DOM element representing a rectangle. The API should support chaining methods that execute sequentially, even if some methods involve asynchronous delays. The class should handle the following methods:

  1. constructor(element): Initializes the chain with a specific DOM element.
  2. .setColor(color): Sets the backgroundColor style property.
  3. .wait(ms): Pauses the execution of the chain for the specified duration.
  4. .shift(x, y): Moves the element by (x, y) pixels using CSS transform (e.g., translate(x, y)).

Requirements

  • The methods must return the RectChain instance to allow for chaining (e.g., new RectChain(el).setColor('red').wait(1000).shift(10, 10)).
  • Operations must be queued and executed one after another in the order they were called.
  • The execution should start automatically or via a .run() method.

Example

const box = document.getElementById('box');
new RectChain(box)
  .setColor('blue')
  .wait(500)
  .shift(100, 0)
  .setColor('green');
// 1. Box turns blue immediately.
// 2. Wait 500ms.
// 3. Box shifts 100px right.
// 4. Box turns green.

Constraints

  • Assume the input element is a valid HTMLDivElement.
  • Your solution should handle the internal queue without blocking the main thread.

Hints

Hint 1

Use a queue to store tasks as functions that return Promises.

Hint 2

Implement a private method that processes the queue recursively or via an async loop, awaiting each operation.

Hint 3

Ensure each method call pushes a new task into the queue and returns 'this' to maintain the chain.

Follow-up questions

  • How would you implement a `.cancel()` method to stop the current queue from executing further?
  • If an error occurs during one step of the chain, how would you handle the subsequent operations?
  • How would you test this class to ensure that the order of operations is deterministic and that the DOM updates are occurring as expected?