Review a generated price search

from Sorting and searching
Node 24 intermediate 9 min 4 issues to find

Review this generated helper before the catalog service uses it.

Build a reusable inclusive price-range lookup over products, preserve caller-owned input order, and return every duplicate boundary price.

JavaScript
function createPriceSearch(products) {
  const source = products;

  function lowerBound(items, target) {
    let low = 0;
    let high = items.length;

    while (low < high) {
      const middle = low + Math.floor((high - low) / 2);
      if (items[middle].price < target) low = middle + 1;
      else high = middle;
    }

    return low;
  }

  return function search(minimum, maximum) {
    source.sort((left, right) => left.price > right.price);
    const start = lowerBound(source, minimum);
    const end = lowerBound(source, maximum);
    return source.slice(start, end);
  };
}

generated code is illustrative, not from any one model

Open in playground
Report an error