Answer:
SELECT n FROM nums
ORDER BY n
LIMIT 2 OFFSET 1;

Return exactly the specified columns and order

SELECT n FROM nums
ORDER BY n
LIMIT 2 OFFSET 1;

Read the schema
Write a query
Check row order and values

Prompt:
nums(n) sorted ascending. Return the second and third smallest n using LIMIT/OFFSET.

Schema and seed data:
CREATE TABLE nums (n INTEGER);
INSERT INTO nums VALUES (9), (1), (4), (2);

OPEN_REASON_RESULT {"passed": true, "rows": [[2], [4]], "expected": [[2], [4]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT region
FROM sales
GROUP BY region
HAVING AVG(amount) >= 10
ORDER BY region;

Return exactly the specified columns and order

SELECT region
FROM sales
GROUP BY region
HAVING AVG(amount) >= 10
ORDER BY region;

Read the schema
Write a query
Check row order and values

Prompt:
sales(region, amount). Return regions whose average amount is at least 10, ordered by region.

Schema and seed data:
CREATE TABLE sales (region TEXT, amount INTEGER);
INSERT INTO sales VALUES ('east', 8), ('east', 12), ('west', 4), ('west', 5), ('north', 20);

OPEN_REASON_RESULT {"passed": true, "rows": [["east"], ["north"]], "expected": [["east"], ["north"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
function sortBy(items, key) {
 return items
 .map((item, index) => ({ item, index }))
 .sort((a, b) => {
 const d = key(a.item) - key(b.item);
 return d !== 0 ? d : a.index - b.index;
 })
 .map((row) => row.item);
}
module.exports = { sortBy };

Node.js standard library only
CommonJS module.exports

function sortBy(items, key) {
  return items
    .map((item, index) => ({ item, index }))
    .sort((a, b) => {
      const d = key(a.item) - key(b.item);
      return d !== 0 ? d : a.index - b.index;
    })
    .map((row) => row.item);
}
module.exports = { sortBy };

const assert = require('assert');
const { sortBy } = require('./solution');
const got = sortBy(
  [{ n: 2, id: 'a' }, { n: 1, id: 'b' }, { n: 2, id: 'c' }],
  (x) => x.n
);
assert.deepStrictEqual(got.map((x) => x.id), ['b', 'a', 'c']);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 1, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement function sortBy(items, key) that returns a new array sorted by the numeric key, stable with respect to original order.


Answer:
function deepFreeze(obj) {
 if (obj === null || typeof obj !== 'object') return obj;
 Object.freeze(obj);
 for (const value of Object.values(obj)) {
 deepFreeze(value);
 }
 return obj;
}
module.exports = { deepFreeze };

Node.js standard library only
CommonJS module.exports

function deepFreeze(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  Object.freeze(obj);
  for (const value of Object.values(obj)) {
    deepFreeze(value);
  }
  return obj;
}
module.exports = { deepFreeze };

const assert = require('assert');
const { deepFreeze } = require('./solution');
const o = { a: { b: 1 } };
deepFreeze(o);
assert.ok(Object.isFrozen(o) && Object.isFrozen(o.a));
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 1, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement deepFreeze(obj) that recursively Object.freeze arrays and plain objects and returns the same reference. Ignore functions.


Answer:
async function pool(limit, factories) {
 const results = new Array(factories.length);
 let next = 0;
 async function worker() {
 while (true) {
 const i = next++;
 if (i >= factories.length) return;
 results[i] = await factories[i]();
 }
 }
 const n = Math.min(limit, factories.length);
 await Promise.all(Array.from({ length: n }, () => worker()));
 return results;
}
module.exports = { pool };

Node.js standard library only
CommonJS module.exports

async function pool(limit, factories) {
  const results = new Array(factories.length);
  let next = 0;
  async function worker() {
    while (true) {
      const i = next++;
      if (i >= factories.length) return;
      results[i] = await factories[i]();
    }
  }
  const n = Math.min(limit, factories.length);
  await Promise.all(Array.from({ length: n }, () => worker()));
  return results;
}
module.exports = { pool };

const assert = require('assert');
const { pool } = require('./solution');
(async () => {
  let current = 0;
  let max = 0;
  const factories = [0, 1, 2, 3, 4].map((i) => async () => {
    current += 1;
    max = Math.max(max, current);
    await new Promise((r) => setTimeout(r, 20));
    current -= 1;
    return i * 2;
  });
  const got = await pool(2, factories);
  assert.deepStrictEqual(got, [0, 2, 4, 6, 8]);
  assert.ok(max <= 2);
  console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 2, failures: 0, errors: 0 }));
})().catch((err) => {
  console.error(err);
  process.exit(1);
});

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement async function pool(limit, factories) where factories is an array of () => Promise. Run at most `limit` at once. Return results in factory order.


Answer:
function mergeQuery(url, params) {
 const u = new URL(url);
 for (const [k, v] of Object.entries(params)) {
 u.searchParams.set(k, v);
 }
 return u.href;
}
module.exports = { mergeQuery };

Node.js standard library only
CommonJS module.exports

function mergeQuery(url, params) {
  const u = new URL(url);
  for (const [k, v] of Object.entries(params)) {
    u.searchParams.set(k, v);
  }
  return u.href;
}
module.exports = { mergeQuery };

const assert = require('assert');
const { mergeQuery } = require('./solution');
const got = mergeQuery('https://example.com/path?q=1&x=2', { x: '9', y: 'z' });
assert.strictEqual(got, 'https://example.com/path?q=1&x=9&y=z');
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 1, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement mergeQuery(url, params) using the WHATWG URL class. Overlay params (object of string values) onto the existing search params and return href without changing other components.


Answer:
function omit(obj, keys) {
 const skip = new Set(keys);
 const out = {};
 for (const [k, v] of Object.entries(obj)) {
 if (!skip.has(k)) out[k] = v;
 }
 return out;
}
module.exports = { omit };

Node.js standard library only
CommonJS module.exports

function omit(obj, keys) {
  const skip = new Set(keys);
  const out = {};
  for (const [k, v] of Object.entries(obj)) {
    if (!skip.has(k)) out[k] = v;
  }
  return out;
}
module.exports = { omit };

const assert = require('assert');
const { omit } = require('./solution');
assert.deepStrictEqual(omit({ a: 1, b: 2, c: 3 }, ['b']), { a: 1, c: 3 });
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 1, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement omit(obj, keys) returning a shallow clone without the listed keys.


Answer:
function lowerBound(arr, target) {
 let lo = 0;
 let hi = arr.length;
 while (lo < hi) {
 const mid = (lo + hi) >> 1;
 if (arr[mid] < target) lo = mid + 1;
 else hi = mid;
 }
 return lo;
}
module.exports = { lowerBound };

Node.js standard library only
CommonJS module.exports

function lowerBound(arr, target) {
  let lo = 0;
  let hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}
module.exports = { lowerBound };

const assert = require('assert');
const { lowerBound } = require('./solution');
assert.strictEqual(lowerBound([1, 3, 3, 7], 3), 1);
assert.strictEqual(lowerBound([1, 3, 7], 8), 3);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 2, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement lowerBound(arr, target) on a sorted numeric array: first index with arr[i] >= target, or arr.length.


Answer:
function debounce(fn, wait) {
 let timer = null;
 return function (...args) {
 const ctx = this;
 clearTimeout(timer);
 timer = setTimeout(() => fn.apply(ctx, args), wait);
 };
}
module.exports = { debounce };

Node.js standard library only
CommonJS module.exports

function debounce(fn, wait) {
  let timer = null;
  return function (...args) {
    const ctx = this;
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(ctx, args), wait);
  };
}
module.exports = { debounce };

const assert = require('assert');
const { debounce } = require('./solution');
(async () => {
  let n = 0;
  const f = debounce(() => { n += 1; }, 30);
  f(); f(); f();
  await new Promise((r) => setTimeout(r, 80));
  assert.strictEqual(n, 1);
  console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 1, failures: 0, errors: 0 }));
})().catch((err) => { console.error(err); process.exit(1); });

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement debounce(fn, wait) using setTimeout. Leading calls reset the timer. Return a function that forwards this and arguments.


Answer:
function parseCsvLine(line) {
 const out = [];
 let cur = '';
 let i = 0;
 let inQuotes = false;
 while (i < line.length) {
 const ch = line[i];
 if (inQuotes) {
 if (ch === '"') {
 if (line[i + 1] === '"') { cur += '"'; i += 2; continue; }
 inQuotes = false; i += 1; continue;
 }
 cur += ch; i += 1; continue;
 }
 if (ch === '"') { inQuotes = true; i += 1; continue; }
 if (ch === ',') { out.push(cur); cur = ''; i += 1; continue; }
 cur += ch; i += 1;
 }
 out.push(cur);
 return out;
}
module.exports = { parseCsvLine };

Node.js standard library only
CommonJS module.exports

function parseCsvLine(line) {
  const out = [];
  let cur = '';
  let i = 0;
  let inQuotes = false;
  while (i < line.length) {
    const ch = line[i];
    if (inQuotes) {
      if (ch === '"') {
        if (line[i + 1] === '"') { cur += '"'; i += 2; continue; }
        inQuotes = false; i += 1; continue;
      }
      cur += ch; i += 1; continue;
    }
    if (ch === '"') { inQuotes = true; i += 1; continue; }
    if (ch === ',') { out.push(cur); cur = ''; i += 1; continue; }
    cur += ch; i += 1;
  }
  out.push(cur);
  return out;
}
module.exports = { parseCsvLine };

const assert = require('assert');
const { parseCsvLine } = require('./solution');
assert.deepStrictEqual(parseCsvLine('a,"b,c","d""e"'), ['a', 'b,c', 'd"e']);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 1, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement parseCsvLine(line) splitting on commas, supporting double-quoted fields with doubled quotes as escape. Return string[].


Answer:
function uniqueStable(xs) {
 const out = [];
 const seen = new Set();
 for (const x of xs) {
 if (seen.has(x)) continue;
 seen.add(x);
 out.push(x);
 }
 return out;
}
module.exports = { uniqueStable };

Node.js standard library only
CommonJS module.exports

function uniqueStable(xs) {
  const out = [];
  const seen = new Set();
  for (const x of xs) {
    if (seen.has(x)) continue;
    seen.add(x);
    out.push(x);
  }
  return out;
}
module.exports = { uniqueStable };

const assert = require('assert');
const { uniqueStable } = require('./solution');
assert.deepStrictEqual(uniqueStable([1, 1, 2, 1, 3]), [1, 2, 3]);
assert.deepStrictEqual(uniqueStable([]), []);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 2, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement uniqueStable(xs) returning first-seen unique values of array xs using SameValueZero (Object.is except -0/+0).


Answer:
function deepGet(obj, path) {
 if (!path) return obj;
 const parts = path.split('.');
 let cur = obj;
 for (const p of parts) {
 if (cur == null || typeof cur !== 'object') return undefined;
 cur = cur[p];
 }
 return cur;
}
module.exports = { deepGet };

Node.js standard library only
CommonJS module.exports

function deepGet(obj, path) {
  if (!path) return obj;
  const parts = path.split('.');
  let cur = obj;
  for (const p of parts) {
    if (cur == null || typeof cur !== 'object') return undefined;
    cur = cur[p];
  }
  return cur;
}
module.exports = { deepGet };

const assert = require('assert');
const { deepGet } = require('./solution');
assert.strictEqual(deepGet({ a: { b: 2 } }, 'a.b'), 2);
assert.strictEqual(deepGet({ a: {} }, 'a.b'), undefined);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 2, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement deepGet(obj, path) where path is 'a.b.c'. Missing keys return undefined. Only plain objects; do not walk arrays as objects beyond numeric keys if present.


Answer:
function chunk(xs, n) {
 if (n < 1) return [];
 const out = [];
 for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));
 return out;
}
module.exports = { chunk };

Node.js standard library only
CommonJS module.exports

function chunk(xs, n) {
  if (n < 1) return [];
  const out = [];
  for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));
  return out;
}
module.exports = { chunk };

const assert = require('assert');
const { chunk } = require('./solution');
assert.deepStrictEqual(chunk([1, 2, 3, 4, 5], 2), [[1, 2], [3, 4], [5]]);
assert.deepStrictEqual(chunk([], 3), []);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 2, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement chunk(xs, n) splitting array xs into arrays of length n (last may be shorter).


Answer:
function once(fn) {
 let called = false;
 let value;
 return function (...args) {
 if (!called) {
 value = fn.apply(this, args);
 called = true;
 }
 return value;
 };
}
module.exports = { once };

Node.js standard library only
CommonJS module.exports

function once(fn) {
  let called = false;
  let value;
  return function (...args) {
    if (!called) {
      value = fn.apply(this, args);
      called = true;
    }
    return value;
  };
}
module.exports = { once };

const assert = require('assert');
const { once } = require('./solution');
let n = 0;
const f = once(() => { n += 1; return n; });
assert.strictEqual(f(), 1);
assert.strictEqual(f(), 1);
assert.strictEqual(n, 1);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 1, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement once(fn) that calls fn at most once and returns the first result thereafter.


Answer:
function parseQuery(q) {
 if (!q) return {};
 const out = {};
 for (const part of q.split('&')) {
 if (!part) continue;
 const i = part.indexOf('=');
 if (i < 0) out[part] = '';
 else out[part.slice(0, i)] = part.slice(i + 1);
 }
 return out;
}
module.exports = { parseQuery };

Node.js standard library only
CommonJS module.exports

function parseQuery(q) {
  if (!q) return {};
  const out = {};
  for (const part of q.split('&')) {
    if (!part) continue;
    const i = part.indexOf('=');
    if (i < 0) out[part] = '';
    else out[part.slice(0, i)] = part.slice(i + 1);
  }
  return out;
}
module.exports = { parseQuery };

const assert = require('assert');
const { parseQuery } = require('./solution');
assert.deepStrictEqual(parseQuery('a=1&b=2'), { a: '1', b: '2' });
assert.deepStrictEqual(parseQuery(''), {});
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 2, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement parseQuery('a=1&b=2') returning {a:'1', b:'2'}. No decoding beyond split on & and first =. Empty string is {}.


Answer:
function range(a, b) {
 if (a > b) return [];
 const out = [];
 for (let i = a; i <= b; i += 1) out.push(i);
 return out;
}
module.exports = { range };

Node.js standard library only
CommonJS module.exports

function range(a, b) {
  if (a > b) return [];
  const out = [];
  for (let i = a; i <= b; i += 1) out.push(i);
  return out;
}
module.exports = { range };

const assert = require('assert');
const { range } = require('./solution');
assert.deepStrictEqual(range(2, 4), [2, 3, 4]);
assert.deepStrictEqual(range(5, 4), []);
console.log('OPEN_REASON_RESULT ' + JSON.stringify({ passed: true, tests_run: 2, failures: 0, errors: 0 }));

Implement the exported function
Keep the public API
Pass the assertions

Prompt: Implement range(a,b) returning [a, a+1, ..., b] inclusive if a<=b else [].


Answer: Arrow functions close over lexical this. Method callbacks keep the instance instead of becoming undefined or the global object.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: Why does an arrow function not get its own `this`, and when is that useful in a method callback?

Solution: function methods get this from the call site. Nested function(){} loses it. An arrow keeps the method's this.


Answer: Control-flow narrowing: the compiler treats x as string in that branch.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: In TypeScript, why does `if (typeof x === 'string')` let you call x.toUpperCase() inside the block?

Solution: typeof guards refine union types. Outside the block x may still be number | string.


Answer: Automatic storage ends at return, so the pointer dangles.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: In C, why is returning the address of a local array undefined behavior?

Solution: Use caller-owned buffers, malloc with documented free, or a static object with a clear lifetime.


Answer: SQL three-valued logic: NULL = NULL is unknown, not true. Use `IS NULL`.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: A query `WHERE name = NULL` returns no rows even when name is null. Why, and what should you write?

Solution: Unknown filters out of WHERE. IS NULL is the null test.


Answer: Clone is correct when you need two owned values. It is a smell when a borrow or redesign would suffice and copies are large.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: When is Clone a legitimate way to keep using a value after a move, and when is it a smell?

Solution: Prefer borrowing. Clone documents an extra allocation or deep copy.


Answer: Defer runs on every return path, so the lock is released after panics and early returns.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: Why is `defer mu.Unlock()` after Lock a common mutex pattern in Go?

Solution: Manual unlock on each return is easy to miss. Defer pairs with Lock at the start of the critical section.


Answer: Equal objects can hash to different buckets, so get after put may miss.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: A Java class overrides equals but not hashCode and is used as a HashMap key. What goes wrong?

Solution: The equals/hashCode contract requires equal objects to share a hash. Override both.


Answer: The guard's destructor unlocks on every exit path, including exceptions.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: In C++, why is std::lock_guard safer than calling mutex.lock() and unlock() by hand?

Solution: RAII ties the lock lifetime to a stack object. Manual unlock is easy to skip.


Answer: any disables checking; a number can reach toUpperCase at runtime.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: A TypeScript function parameter is typed `any` and then `.toUpperCase()` is called. Why is that a hole?

Solution: Use unknown and narrow, or a precise union. any is an escape hatch.


Answer: WHERE runs before grouping. HAVING filters after aggregation.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: Why can't `WHERE COUNT(*) > 1` filter groups, and what clause does?

Solution: GROUP BY then HAVING COUNT(*) > 1.


Answer: Nullable types are distinct; the compiler requires a null check or assertion.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: In Kotlin, why is `String?` not assignable to `String` without a check?

Solution: That is the point of null safety. Use ?. or a smart cast after `if (x != null)`.


Answer: Lazy evaluation only forces the prefix take needs.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: Why can `take 5 [1..]` terminate in Haskell even though `[1..]` is infinite?

Solution: The rest of the list is not computed. A strict language would loop.


Answer: The shell splits on spaces and rm sees two arguments. Use `rm -- "$file"`.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: A script does `rm $file` and `$file` is `a b.txt`. What happens, and how do you quote?

Solution: Word-splitting is not a filename parser. Quote expansions.


Answer: Dispose runs at the end of the block, including on exceptions.

Original Open Reason wording. Not copied from vendor docs.

Name the language rule
State the consequence
Give the repair or use

Prompt: Why does `using` on an IDisposable in C# resemble Python's `with`?

Solution: Both are RAII-style resource scopes. Prefer using over manual Dispose.