25 Topics
Chapter•180 Minutes

25 Progressive JavaScript Coding Questions (Easy to Difficult)

A 25-question coding bank structured from basic JavaScript string/array manipulations to advanced asynchronous control flow, custom polyfills, and engine metaprogramming.

Q1: Reverse a String Without Built-In Reverse

To reverse a string manually, iterate backward from the last character to the first, appending each character to a new string. This demonstrates basic iteration and string accumulation.

Manual String Reversal
function reverseString(str) {
  let reversed = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

console.log(reverseString('hello')); // 'olleh'

By looping from str.length - 1 down to 0, each character is appended in reverse order without using Array.prototype.reverse().

Key Takeaways
  • Iterates backward from the end of the string to assemble a new reversed string.

  • Runs with O(n) time complexity and O(n) space complexity.

Knowledge Check

What is the time complexity of reversing a string of length n character-by-character?

Q2: Classic FizzBuzz Implementation

Output numbers from 1 to N, replacing multiples of 3 with 'Fizz', 5 with 'Buzz', and multiples of both with 'FizzBuzz'. Check compound conditions (multiples of 15) before individual factors.

FizzBuzz Loop
function fizzBuzz(n) {
  const result = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) result.push('FizzBuzz');
    else if (i % 3 === 0) result.push('Fizz');
    else if (i % 5 === 0) result.push('Buzz');
    else result.push(i.toString());
  }
  return result;
}

console.log(fizzBuzz(15));

Evaluating i % 15 first prevents multiples of both 3 and 5 from matching the earlier single-factor branches.

Key Takeaways
  • Check for combined conditions (i % 15 === 0) before individual conditions.

  • Demonstrates basic modulo arithmetic and control flow branching.

Knowledge Check

Why must the condition for 15 (or both 3 and 5) be checked first in FizzBuzz?

Q3: Check if a String is a Palindrome

Clean non-alphanumeric characters and convert to lower case, then use a two-pointer approach moving toward the center to check if the string reads identically forward and backward.

Two-Pointer Palindrome Validation
function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  let left = 0;
  let right = cleaned.length - 1;
  while (left < right) {
    if (cleaned[left] !== cleaned[right]) return false;
    left++;
    right--;
  }
  return true;
}

console.log(isPalindrome('A man, a plan, a canal: Panama')); // true

Two pointers move inward from opposite ends, allowing early exit as soon as a non-matching character pair is found.

Key Takeaways
  • Sanitizes strings using Regular Expressions prior to checking.

  • Uses a two-pointer approach to compare characters from opposite ends toward the center.

Knowledge Check

What is the primary benefit of a two-pointer approach over str === str.split('').reverse().join('')?

Q4: Find Minimum and Maximum Values in an Array

Find both min and max values in a single pass across the array without relying on spread syntax with Math.min/Math.max, which can overflow the call stack on large arrays.

Single-Pass Min/Max Finder
function findMinMax(arr) {
  if (!arr.length) return { min: undefined, max: undefined };
  let min = arr[0];
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) min = arr[i];
    if (arr[i] > max) max = arr[i];
  }
  return { min, max };
}

console.log(findMinMax([3, 1, 9, 4, 2])); // { min: 1, max: 9 }

Iterating once updates min and max tracking variables in O(n) time and O(1) auxiliary space.

Key Takeaways
  • Performs single-pass O(n) iteration to update bounds.

  • Avoids Math.max(...arr) which can throw a stack overflow error on very large arrays.

Knowledge Check

Why can Math.max(...largeArray) fail on extremely large arrays (e.g. 100,000+ elements)?

Q5: Chunk an Array into Sub-Arrays of Fixed Size

Split an array into smaller sub-arrays of a target size by iterating through the source array in increments of the chunk size and calling Array.prototype.slice().

Array Chunking Helper
function chunkArray(arr, size) {
  const chunked = [];
  for (let i = 0; i < arr.length; i += size) {
    chunked.push(arr.slice(i, i + size));
  }
  return chunked;
}

console.log(chunkArray([1, 2, 3, 4, 5], 2)); // [[1, 2], [3, 4], [5]]

By incrementing the loop index by size each iteration, slice() extracts sub-arrays of exact length.

Key Takeaways
  • Advances loop pointer by size steps.

  • Array.prototype.slice extracts chunks cleanly without mutating the source array.

Knowledge Check

What is the result of chunkArray([1, 2, 3, 4, 5], 2)?

Q6: Count Character Frequencies in a String

Count the occurrence of each character in a string by accumulating counts inside a plain object map, initializing unseen characters to zero.

Character Frequency Counter
function charFrequency(str) {
  const freq = {};
  for (let char of str) {
    freq[char] = (freq[char] || 0) + 1;
  }
  return freq;
}

console.log(charFrequency('hello')); // { h: 1, e: 1, l: 2, o: 1 }

The expression (freq[char] || 0) ensures that unvisited characters start at 0 before adding 1.

Key Takeaways
  • Uses logical OR (||) to initialize missing object keys to zero.

  • Runs in linear O(n) time complexity relative to string length.

Knowledge Check

What value does freq[char] || 0 evaluate to if char is not yet present in the freq map?

Q7: Remove Duplicate Values from an Array

Deduplicate elements in an array using an ES6 Set for linear performance, or Array.prototype.filter() with indexOf() for a single-line functional approach.

Array Deduplication Approaches
// Approach 1: ES6 Set (Optimal O(n))
const uniqueSet = (arr) => [...new Set(arr)];

// Approach 2: Array filter (O(n²))
const uniqueFilter = (arr) => arr.filter((item, index) => arr.indexOf(item) === index);

console.log(uniqueSet([1, 2, 2, 3, 4, 4])); // [1, 2, 3, 4]

ES6 Set automatically discards duplicate values in linear time, while filter + indexOf scans the array repeatedly.

Key Takeaways
  • Set approach provides O(n) time complexity.

  • filter + indexOf provides O(n²) time complexity due to internal lookup overhead.

Knowledge Check

Why is the Set approach preferred over filter + indexOf for large arrays?

Q8: Invert Keys and Values of an Object

Swap the keys and values of a plain object into a new object using a for...in loop combined with a hasOwnProperty check to ignore prototype properties.

Object Key-Value Inversion
function invertObject(obj) {
  const inverted = {};
  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      inverted[obj[key]] = key;
    }
  }
  return inverted;
}

console.log(invertObject({ a: 'x', b: 'y' })); // { x: 'a', y: 'b' }

Maps each value obj[key] as a key in the new object, assigning the original key string as its value.

Key Takeaways
  • Swaps keys and values into a new object.

  • Uses hasOwnProperty guard to prevent iterating inherited prototype properties.

Knowledge Check

What happens if an object contains multiple duplicate values during inversion (e.g. { a: 1, b: 1 })?

Q9: Implement Custom pick and omit Object Helpers

Build pick(obj, keys) to extract specific properties into a new object, and omit(obj, keys) to create a copy that excludes specified keys.

Object Pick and Omit Utility
function pick(obj, keys) {
  return keys.reduce((acc, key) => {
    if (key in obj) acc[key] = obj[key];
    return acc;
  }, {});
}

function omit(obj, keys) {
  const keySet = new Set(keys);
  return Object.keys(obj).reduce((acc, key) => {
    if (!keySet.has(key)) acc[key] = obj[key];
    return acc;
  }, {});
}

const user = { id: 1, name: 'Alex', role: 'admin' };
console.log(pick(user, ['name', 'role'])); // { name: 'Alex', role: 'admin' }
console.log(omit(user, ['role']));         // { id: 1, name: 'Alex' }

pick filters down to specified keys, while omit uses a Set lookup to drop listed keys efficiently.

Key Takeaways
  • Reduces object keys dynamically.

  • Using a Set in omit allows O(1) key exclusion checks.

Knowledge Check

What is the benefit of passing keys as a Set inside the omit function?

Q10: Implement Infinite Curried Addition sum(1)(2)(3)...()

Create a function that continuously accumulates numbers across chained function calls until called with no arguments to signal termination.

Infinitely Curried Sum
function sum(a) {
  return function(b) {
    if (b !== undefined) {
      return sum(a + b);
    }
    return a;
  };
}

console.log(sum(1)(2)(3)()); // 6
console.log(sum(5)(10)());   // 15

Each invocation returns a new sum function wrapping the updated total until b === undefined triggers the final total.

Key Takeaways
  • Uses closure state to accumulate sum values across chained calls.

  • Terminates recursive currying when invoked without arguments (b === undefined).

Knowledge Check

What acts as the base termination signal for ending the sum currying chain above?

Q11: Implement Promise Timeout (Cancel Race)

Wrap a target Promise with a timeout reject mechanism using Promise.race, ensuring the operation fails if it exceeds a specified delay threshold.

Promise Timeout Wrapper
function promiseWithTimeout(promise, ms) {
  const timeout = new Promise((_, reject) => {
    setTimeout(() => reject(new Error(`Operation timed out after ${ms}ms`)), ms);
  });
  return Promise.race([promise, timeout]);
}

const slowTask = new Promise(res => setTimeout(() => res('Done'), 2000));
promiseWithTimeout(slowTask, 1000).catch(err => console.error(err.message));

Promise.race resolves with the target result if it completes before the setTimeout reject fires.

Key Takeaways
  • Promise.race resolves or rejects as soon as any promise in the array settles.

  • Combines target promise against a timer reject promise.

Knowledge Check

If the main promise resolves in 500ms and the timeout is set to 1000ms, what is the output of Promise.race?

Q12: Write a Custom Function.prototype.bind Polyfill

Implement a custom version of Function.prototype.bind that captures context and initial bound arguments, returning a function that accepts additional arguments at call time.

Function bind Polyfill
Function.prototype.myBind = function(context, ...boundArgs) {
  const fn = this;
  if (typeof fn !== 'function') {
    throw new TypeError('Bind must be called on a function');
  }
  return function(...args) {
    return fn.apply(context, [...boundArgs, ...args]);
  };
};

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}
const bound = greet.myBind({ name: 'Alex' }, 'Hello');
console.log(bound('!')); // 'Hello, Alex!'

myBind returns a wrapper that applies the stored context and combines initial boundArgs with invocation arguments.

Key Takeaways
  • Captures this target function inside a closure.

  • Concatenates initial boundArgs with execution call args during invocation.

Knowledge Check

How are initial arguments passed to myBind merged with arguments passed to the bound execution function?

Q13: Write a URL Query String Parser and Builder

Implement helper functions to convert URL query parameters into an object map and convert an object map back into an encoded URL query string.

Query Parser and Stringifier
function parseQuery(str) {
  if (!str) return {};
  const queryString = str.startsWith('?') ? str.slice(1) : str;
  return queryString.split('&').reduce((acc, param) => {
    const [key, value] = param.split('=');
    if (key) acc[decodeURIComponent(key)] = decodeURIComponent(value || '');
    return acc;
  }, {});
}

function stringifyQuery(obj) {
  return Object.entries(obj)
    .map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
    .join('&');
}

console.log(parseQuery('?name=Alex&age=25')); // { name: 'Alex', age: '25' }
console.log(stringifyQuery({ a: '1', b: '2' })); // 'a=1&b=2'

Splitting by delimiters extracts key-value pairs while URI encoding functions prevent character corruption.

Key Takeaways
  • Processes delimiter split strings using split('&') and split('=').

  • Encodes and decodes special URI characters using encodeURIComponent and decodeURIComponent.

Knowledge Check

Why must encodeURIComponent be used when stringifying query parameters?

Q14: Implement an Async Publish-Subscribe Bus

Create an event bus that supports asynchronous subscriber callbacks, returning a promise from publish() that resolves once all subscriber callbacks settle.

Async Event Bus
class AsyncEventBus {
  constructor() {
    this.subscribers = new Map();
  }

  subscribe(event, callback) {
    if (!this.subscribers.has(event)) this.subscribers.set(event, new Set());
    this.subscribers.get(event).add(callback);
    return () => this.subscribers.get(event).delete(callback);
  }

  async publish(event, data) {
    if (!this.subscribers.has(event)) return [];
    const callbacks = Array.from(this.subscribers.get(event));
    const promises = callbacks.map(cb => Promise.resolve().then(() => cb(data)));
    return Promise.all(promises);
  }
}

Publishing wraps each callback in a Promise, allowing Promise.all to await all subscriber operations concurrently.

Key Takeaways
  • Returns an un-subscribe teardown closure upon registration.

  • Uses Promise.all to execute and await subscriber handlers concurrently during publication.

Knowledge Check

What is the return result of publishing an event in the AsyncEventBus above?

Q15: Write a Simple Virtual DOM Render Function

Implement a render(vnode) function that converts Virtual DOM element objects ({ type, props, children }) or text primitives into real DOM Node instances.

VNode to Real DOM Compiler
function render(vnode) {
  if (typeof vnode === 'string' || typeof vnode === 'number') {
    return document.createTextNode(String(vnode));
  }
  
  const el = document.createElement(vnode.type);
  
  if (vnode.props) {
    Object.entries(vnode.props).forEach(([key, val]) => {
      if (key.startsWith('on')) {
        el.addEventListener(key.slice(2).toLowerCase(), val);
      } else {
        el.setAttribute(key, val);
      }
    });
  }
  
  if (vnode.children) {
    vnode.children.forEach(child => el.appendChild(render(child)));
  }
  
  return el;
}

Recursively converts element descriptors into real DOM nodes, registering event listeners for 'on' props.

Key Takeaways
  • Recursively processes tree node structures using DOM API creation calls.

  • Distinguishes text nodes, attribute props, and on event listener bindings.

Knowledge Check

How does the render function handle event props like onClick: fn?

Q16: Implement an Async Waterfall Sequencer

Build an async pipeline helper that executes an array of asynchronous functions sequentially, passing the output of each function as input to the next.

Sequential Async Pipeline
function asyncWaterfall(tasks, initialValue) {
  return tasks.reduce((promiseChain, currentTask) => {
    return promiseChain.then(result => currentTask(result));
  }, Promise.resolve(initialValue));
}

const add2 = async (x) => x + 2;
const mult3 = async (x) => x * 3;

asyncWaterfall([add2, mult3], 5).then(console.log); // (5 + 2) * 3 = 21

Array.reduce builds a continuous Promise chain where each task executes only after the previous task resolves.

Key Takeaways
  • Chains Promise resolution steps sequentially using Array.prototype.reduce.

  • Executes asynchronous pipeline processing, passing forward computed outcomes.

Knowledge Check

How does asyncWaterfall guarantee sequential execution over concurrent Promise.all execution?

Q17: Implement Deep Freeze for Complete Immutability

Extend Object.freeze() to recursively freeze all nested object and array properties to guarantee complete object graph immutability.

Recursive Deep Freeze
function deepFreeze(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  
  Object.freeze(obj);
  
  Object.getOwnPropertyNames(obj).forEach(prop => {
    const val = obj[prop];
    if (val !== null && typeof val === 'object' && !Object.isFrozen(val)) {
      deepFreeze(val);
    }
  });
  
  return obj;
}

const config = deepFreeze({ api: { host: 'localhost' } });
// config.api.host = 'remote'; // Throws TypeError in strict mode

Deep freeze invokes Object.freeze() at the current level, then recursively traverses and freezes all nested object properties.

Key Takeaways
  • Native Object.freeze() is shallow and does not freeze nested object properties.

  • Recursively freezes child objects to guarantee deep immutability.

Knowledge Check

What occurs when attempting to mutate a property on a deepFrozen object in strict mode?

Q18: Implement a Time and Size Batch Request Scheduler

Build a batcher that accumulates incoming items and flushes them to a processing handler whenever maximum batch size is reached OR maximum delay time elapses.

Batch Request Scheduler
class BatchScheduler {
  constructor(batchHandler, maxSize = 5, maxDelay = 100) {
    this.handler = batchHandler;
    this.maxSize = maxSize;
    this.maxDelay = maxDelay;
    this.batch = [];
    this.timer = null;
  }

  add(item) {
    this.batch.push(item);
    if (this.batch.length >= this.maxSize) {
      this.flush();
    } else if (!this.timer) {
      this.timer = setTimeout(() => this.flush(), this.maxDelay);
    }
  }

  flush() {
    if (this.timer) clearTimeout(this.timer);
    this.timer = null;
    if (this.batch.length > 0) {
      const itemsToProcess = [...this.batch];
      this.batch = [];
      this.handler(itemsToProcess);
    }
  }
}

Reaching maxSize triggers an immediate flush; otherwise a timer schedules a flush after maxDelay.

Key Takeaways
  • Dual trigger batching: flushes immediately on max size or automatically on timer expiration.

  • Optimizes network requests by combining multiple individual calls into single batch payload calls.

Knowledge Check

Why is the timer cleared inside flush() during max size execution triggers?

Q19: Calculate Structural Difference Between Two Objects

Implement diffObjects(obj1, obj2) to compare two objects recursively and return a summary of added, removed, and updated properties.

Object Diffing Utility
function diffObjects(obj1, obj2) {
  const diff = {};
  const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
  
  for (let key of allKeys) {
    if (!(key in obj1)) {
      diff[key] = { status: 'ADDED', value: obj2[key] };
    } else if (!(key in obj2)) {
      diff[key] = { status: 'REMOVED', value: obj1[key] };
    } else if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object' && obj1[key] !== null && obj2[key] !== null) {
      const nestedDiff = diffObjects(obj1[key], obj2[key]);
      if (Object.keys(nestedDiff).length > 0) diff[key] = nestedDiff;
    } else if (obj1[key] !== obj2[key]) {
      diff[key] = { status: 'UPDATED', oldValue: obj1[key], newValue: obj2[key] };
    }
  }
  return diff;
}

Collects keys across both objects to determine property additions, removals, and value mutations recursively.

Key Takeaways
  • Combines key sets to evaluate deletions, additions, and mutations.

  • Recursively evaluates nested object structures to identify structural changes.

Knowledge Check

How does the diffObjects algorithm identify a key that was REMOVED in obj2?

Q20: Create a Reactive Auto-Tracking State Store Using Proxy

Create an automated reactive store where accessing properties inside a watchEffect callback registers dependencies and mutating properties triggers re-execution.

Proxy-Based Reactive State Store
let activeEffect = null;

function createReactiveStore(initialState) {
  const deps = new Map();

  return new Proxy(initialState, {
    get(target, key, receiver) {
      if (activeEffect) {
        if (!deps.has(key)) deps.set(key, new Set());
        deps.get(key).add(activeEffect);
      }
      return Reflect.get(target, key, receiver);
    },
    set(target, key, value, receiver) {
      const result = Reflect.set(target, key, value, receiver);
      if (deps.has(key)) {
        deps.get(key).forEach(effect => effect());
      }
      return result;
    }
  });
}

function watchEffect(effect) {
  activeEffect = effect;
  effect();
  activeEffect = null;
}

Active effects trigger getter traps to register keys as dependencies, allowing setter traps to re-run affected callbacks on change.

Key Takeaways
  • Core architecture powering reactivity in modern frameworks (e.g. Vue 3 Reactivity).

  • get traps track active effect dependencies; set traps notify and re-run dependent effects.

Knowledge Check

How does watchEffect automatically detect which store keys an effect function depends on?

Q21: Implement Custom myInstanceOf Operator

Replicate the behavior of the instanceof operator by traversing the prototype chain of an object to check for matching constructor prototypes.

Custom instanceof Implementation
function myInstanceOf(obj, constructor) {
  if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {
    return false;
  }
  
  let proto = Object.getPrototypeOf(obj);
  const targetProto = constructor.prototype;
  
  while (proto !== null) {
    if (proto === targetProto) return true;
    proto = Object.getPrototypeOf(proto);
  }
  
  return false;
}

console.log(myInstanceOf([], Array));  // true
console.log(myInstanceOf([], Object)); // true

Walks Object.getPrototypeOf(obj) upward until finding constructor.prototype or reaching the null prototype root.

Key Takeaways
  • Traverses Object.getPrototypeOf(obj) upward step by step.

  • Returns true if target constructor.prototype is found anywhere along the prototype chain.

Knowledge Check

What value does Object.getPrototypeOf() return when called at the top termination point of the prototype chain?

Q22: Implement Custom Promise.allSettled Polyfill

Polyfill Promise.allSettled using Promise.all by wrapping individual inner promises so rejections resolve into structured result objects.

Promise.allSettled Polyfill
function myPromiseAllSettled(promises) {
  return Promise.all(
    promises.map(p => 
      Promise.resolve(p)
        .then(value => ({ status: 'fulfilled', value }))
        .catch(reason => ({ status: 'rejected', reason }))
    )
  );
}

myPromiseAllSettled([Promise.resolve(1), Promise.reject('err')]).then(console.log);

Handling rejections inside inner .catch() blocks ensures Promise.all receives only resolved outcome descriptors.

Key Takeaways
  • Wraps each inner promise in .then() and .catch() blocks that map settlement to objects.

  • Leverages Promise.all over mapped promises since wrapped promises never reject.

Knowledge Check

Why does myPromiseAllSettled wrapping allow Promise.all to resolve without rejecting early?

Q23: Build a Basic Virtual DOM Tree Diffing Engine

Build a diffing engine that compares old and new Virtual DOM node trees recursively, generating patch descriptions for updates, replacements, and removals.

VNode Diffing Algorithm
function diff(oldVNode, newVNode) {
  if (newVNode === undefined) {
    return { type: 'REMOVE' };
  }
  if (typeof oldVNode === 'string' || typeof newVNode === 'string') {
    if (oldVNode !== newVNode) return { type: 'TEXT', text: newVNode };
    return null;
  }
  if (oldVNode.type !== newVNode.type) {
    return { type: 'REPLACE', newVNode };
  }
  
  const propsDiff = diffProps(oldVNode.props || {}, newVNode.props || {});
  const childrenDiff = diffChildren(oldVNode.children || [], newVNode.children || []);
  
  return {
    type: 'UPDATE',
    props: propsDiff,
    children: childrenDiff
  };
}

function diffProps(oldProps, newProps) {
  const patches = [];
  for (let key in newProps) {
    if (newProps[key] !== oldProps[key]) patches.push({ key, value: newProps[key] });
  }
  for (let key in oldProps) {
    if (!(key in newProps)) patches.push({ key, value: undefined });
  }
  return patches;
}

function diffChildren(oldChildren, newChildren) {
  const max = Math.max(oldChildren.length, newChildren.length);
  const childPatches = [];
  for (let i = 0; i < max; i++) {
    childPatches.push(diff(oldChildren[i], newChildren[i]));
  }
  return childPatches;
}

Compares VNodes recursively, returning REPLACE patches when tag types change or UPDATE patches for modified props/children.

Key Takeaways
  • Compares VNodes recursively to calculate minimal structural edits.

  • Replaces entire subtrees when VNode type tags differ.

Knowledge Check

What patch action is returned when comparing two VNodes with different element type tags (e.g. div vs section)?

Q24: Build a Priority-Based Asynchronous Job Queue

Implement an asynchronous job queue that sorts queued tasks by numeric priority values so higher priority jobs execute first under concurrency limits.

Priority Async Queue
class PriorityAsyncQueue {
  constructor(concurrency = 2) {
    this.concurrency = concurrency;
    this.running = 0;
    this.heap = [];
  }

  enqueue(task, priority = 0) {
    return new Promise((resolve, reject) => {
      this.heap.push({ task, priority, resolve, reject });
      this.heap.sort((a, b) => b.priority - a.priority);
      this.processNext();
    });
  }

  processNext() {
    if (this.running >= this.concurrency || this.heap.length === 0) return;
    
    const { task, resolve, reject } = this.heap.shift();
    this.running++;
    
    Promise.resolve(task())
      .then(resolve)
      .catch(reject)
      .finally(() => {
        this.running--;
        this.processNext();
      });
  }
}

Tasks are sorted by priority score upon insertion, ensuring highest-priority items shift out first when worker slots open.

Key Takeaways
  • Orders pending tasks by priority before processing.

  • Enforces concurrency limits while processing high-priority tasks first.

Knowledge Check

In what order are pending tasks processed by the PriorityAsyncQueue above?

Q25: Build a Custom Stream Transform Pipeline Component

Create a data stream processor that processes stream chunks sequentially through composed async transform middleware, allowing chunks to be modified or filtered out.

Transform Stream Pipeline
class DataPipeline {
  constructor() {
    this.transforms = [];
  }

  use(transformFn) {
    this.transforms.push(transformFn);
    return this;
  }

  async execute(sourceDataStream) {
    const results = [];
    for (let chunk of sourceDataStream) {
      let currentData = chunk;
      let skipped = false;
      
      for (let transform of this.transforms) {
        currentData = await transform(currentData);
        if (currentData === null || currentData === undefined) {
          skipped = true;
          break;
        }
      }
      
      if (!skipped) {
        results.push(currentData);
      }
    }
    return results;
  }
}

const pipeline = new DataPipeline()
  .use(async x => x * 2)
  .use(async x => x > 5 ? x : null);

pipeline.execute([1, 2, 4]).then(console.log); // [8]

Applies sequential transforms to each chunk. Returning null inside any transform halts the middleware chain and drops the chunk.

Key Takeaways
  • Pipes individual stream chunks through sequentially composed transformation middleware.

  • Supports filtering chunks from the stream when transform functions return null or undefined.

Knowledge Check

What happens when a transformation function in the pipeline returns null for a specific chunk?