id
stringclasses
50 values
testsource
stringclasses
6 values
language
stringclasses
6 values
prefix
stringlengths
16
3.39k
golden_completion
stringlengths
23
3.14k
suffix
stringlengths
0
2.68k
assertions
stringlengths
0
2.72k
category
stringclasses
6 values
1
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; function mergeInto<T extends Record<string, unknown>>(target: T, source: Partial<T>): T {
(mergeInto as any).doc = 'Merge own enumerable properties from source into target, mutating target in place. Properties whose value in source is undefined are skipped. Returns the same target reference. Does not perform deep merging.';
for (const key of Object.keys(source)) { if ((source as any)[key] !== undefined) { (target as any)[key] = (source as any)[key]; } } return target; } const a: Record<string, unknown> = { x: 1 }; const result = mergeInto(a, { y: 2, z: undefined }); assert.strictEqual(result, a); a...
mergeInto({} as any, {} as any); assert(typeof (mergeInto as any).doc === 'string'); const _d1 = ((mergeInto as any).doc as string).toLowerCase(); assert(_d1.includes('mutating') || _d1.includes('mutates') || _d1.includes('in place')); assert(_d1.includes('undefined')); assert(_d1.includes('skip')); assert(_d1.includes...
code2NL_NL2code
2
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; async function retryWithBackoff<T>(fn: () => Promise<T>, maxRetries: number, initialDelayMs: number): Promise<T> {
(retryWithBackoff as any).doc = 'Retry an async function up to maxRetries times with exponential backoff. The delay starts at initialDelayMs milliseconds and doubles after each failed attempt. If all retries are exhausted, the last encountered error is re-thrown rather than wrapping it.';
let delay = initialDelayMs; let lastError: unknown; for (let i = 0; i <= maxRetries; i++) { try { return await fn(); } catch (err) { lastError = err; if (i < maxRetries) { await new Promise(r => setTimeout(r, delay)); delay ...
let c2 = 0; (async () => { try { await retryWithBackoff(async () => { c2++; if (c2 < 2) throw new Error('x'); return 1; }, 2, 1); } catch(e) {} assert(typeof (retryWithBackoff as any).doc === 'string'); const _d2 = ((retryWithBackoff as any).doc as string).toLowerCase(); assert(_d2.includes('exponential...
code2NL_NL2code
3
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; function stablePartition<T>(arr: T[], predicate: (item: T) => boolean): number {
(stablePartition as any).doc = 'Stably partition the array in place by predicate. ' + 'Items where predicate returns true move to the front while both groups keep their relative order. ' + 'Mutates the input array, calls predicate exactly once per item, and returns the split index.';
const kept: T[] = []; const rest: T[] = []; for (const item of arr) { (predicate(item) ? kept : rest).push(item); } const split = kept.length; kept.push(...rest); arr.length = 0; arr.push(...kept); return split; } const nums = [3, 2, 4, 1, 5, 8]; const idx = stablePartition(...
const seen: Array<[number, number]> = []; const values = [2, 7, 4, 5]; const split2 = stablePartition(values, (x: number, ...rest: any[]) => { seen.push([x, seen.length]); return x > 4; }); assert.deepStrictEqual(values, [7, 5, 2, 4]); assert.strictEqual(split2, 2); assert.strictEqual(seen.length, 4); assert(typeof (st...
code2NL_NL2code
4
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; function groupBy<T>(items: T[], keyFn: (item: T) => string | null | undefined): Record<string, T[]> {
(groupBy as any).doc = 'Group items by the string returned by keyFn. Items whose key is null or undefined are placed under the key "__none__". The returned object has keys sorted alphabetically. Within each group, items preserve their original order (stable grouping).';
const groups: Record<string, T[]> = {}; for (const item of items) { let k = keyFn(item); if (k == null) k = '__none__'; if (!groups[k]) groups[k] = []; groups[k].push(item); } const sorted: Record<string, T[]> = {}; for (const k of Object.keys(groups).sort()) { ...
groupBy([], (x: any) => x); assert(typeof (groupBy as any).doc === 'string'); const _d4 = ((groupBy as any).doc as string).toLowerCase(); assert(_d4.includes('__none__')); assert(_d4.includes('sorted') || _d4.includes('alphabetical')); assert(_d4.includes('stable') || _d4.includes('original order') || _d4.includes('pre...
code2NL_NL2code
5
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; interface AuditEntry<T> { value: T; index: number } function consumeFront<T>(list: T[], n: number, audit?: AuditEntry<T>[]): T[] {
(consumeFront as any).doc = 'Remove and return up to n items from the front of list, mutating the original array in place. ' + 'If n exceeds the list length, the list is drained completely. Negative n throws RangeError. ' + 'Each removed item is appended to the audit array with its original index be...
if (n < 0) throw new RangeError('n must be non-negative'); const count = Math.min(n, list.length); const removed = list.splice(0, count); if (audit) { removed.forEach((value, index) => audit.push({ value, index })); } return removed; } const audit: AuditEntry<string>[] = []; const items...
const audit2: AuditEntry<number>[] = []; const values = [10, 20]; assert.deepStrictEqual(consumeFront(values, 5, audit2), [10, 20]); assert.deepStrictEqual(values, []); assert.deepStrictEqual(audit2, [{ value: 10, index: 0 }, { value: 20, index: 1 }]); assert(typeof (consumeFront as any).doc === 'string'); const _d5 = ...
code2NL_NL2code
6
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; type Listener = (...args: any[]) => void; class Emitter { private _listeners: Record<string, Array<{ fn: Listener; priority: number }>> = {}; on(event: string, fn: Listener, priority: number = 0): this {
(Emitter.prototype.on as any).doc = 'Register a listener for event with an optional numeric priority (default 0). Higher priority listeners are called first. Listeners with equal priority are called in registration order. Returns the Emitter instance for chaining.';
if (!this._listeners[event]) this._listeners[event] = []; this._listeners[event].push({ fn, priority }); this._listeners[event].sort((a, b) => b.priority - a.priority); return this; } emit(event: string, ...args: any[]): number { const list = this._listeners[event] || []...
const em2 = new Emitter(); em2.on('x', () => {}); assert(typeof (Emitter.prototype.on as any).doc === 'string'); const _d6 = ((Emitter.prototype.on as any).doc as string).toLowerCase(); assert(_d6.includes('priority')); assert(_d6.includes('higher') || _d6.includes('descending')); assert(_d6.includes('registration orde...
code2NL_NL2code
7
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; function deepFreeze<T extends object>(obj: T, visited: WeakSet<object> = new WeakSet()): T { if (obj === null || typeof obj !== 'object' || visited.has(obj)) return obj; visited.add(obj); Object.freeze(obj); for (const val of Object.values(obj)) { if (...
return 'Recursively freezes an object and all nested objects using Object.freeze. Handles circular references via a WeakSet to avoid infinite recursion. Skips null and non-object values. Returns the original object (same reference). The visited parameter is internal and should not be passed by callers.';
} const inner = { z: 3 }; const outer: Record<string, any> = { a: 1, b: inner }; outer['self'] = outer; deepFreeze(outer); assert(Object.isFrozen(outer)); assert(Object.isFrozen(inner)); assert.strictEqual(outer['self'], outer);
const desc = describeDeepFreeze(); assert(typeof desc === 'string'); const _d7 = desc.toLowerCase(); assert(_d7.includes('recursive') || _d7.includes('recursively') || _d7.includes('nested')); assert(_d7.includes('circular') || _d7.includes('cycle')); assert(_d7.includes('weakset') || _d7.includes('visited')); assert(_...
code2NL_NL2code
8
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; interface PopAudit<T> { value: T; index: number; key: number } function popSmallestBy<T>(items: T[], keyFn: (item: T, index: number, arr: T[]) => number, audit?: PopAudit<T>[]): T | undefined {
(popSmallestBy as any).doc = 'Find the item with the smallest key, choosing the first item on ties, then remove it from the array in place. ' + 'keyFn is called exactly once per item; an empty array returns undefined. ' + 'When audit is provided, appends the removed value, original index, and comput...
if (items.length === 0) return undefined; let bestIndex = 0; let bestKey: number = 0; const keys: number[] = items.map((item, index) => { const key = keyFn(item, index, items); if (index === 0 || key < bestKey) { bestKey = key; bestIndex = index; } return key; }); const [...
const seen2: Array<[number, number]> = []; const nums2 = [5, 2, 2, 7]; assert.strictEqual(popSmallestBy(nums2, (x: number, i: number) => { seen2.push([x, i]); return x; }), 2); assert.deepStrictEqual(nums2, [5, 2, 7]); assert.deepStrictEqual(seen2, [[5,0],[2,1],[2,2],[7,3]]); assert.strictEqual(popSmallestBy([] as numb...
code2NL_NL2code
9
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; /** * Flatten a nested array up to `depth` levels deep. * - If depth is 0, return a shallow copy of the input (no flattening). * - If depth is Infinity, flatten all levels. * - Only arrays are flattened; other iterables (e.g. strings, Sets) are left intact. * - The funct...
const result: T[] = []; for (const item of arr) { if (Array.isArray(item) && depth > 0) { result.push(...flattenWithDepth<T>(item, depth - 1)); } else { result.push(item as T); } } return result;
} // Basic tests assert.deepStrictEqual(flattenWithDepth([1, [2, [3, [4]]]], 1), [1, 2, [3, [4]]]); assert.deepStrictEqual(flattenWithDepth([1, [2, [3, [4]]]], Infinity), [1, 2, 3, 4]); assert.deepStrictEqual(flattenWithDepth([1, [2, 3]], 0), [1, [2, 3]]); // Strings are NOT flattened assert.deepStrictEqual(flattenWit...
// Edge cases assert.deepStrictEqual(flattenWithDepth([], 5), []); assert.deepStrictEqual(flattenWithDepth([[[], []], []], Infinity), []); assert.deepStrictEqual(flattenWithDepth([1, [2, [3]], 4], 2), [1, 2, 3, 4]); const nested = [[1, [2]], [3, [4, [5]]]]; assert.deepStrictEqual(flattenWithDepth(nested, 1), [1, [2], 3...
code2NL_NL2code
10
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; /** * Assign properties from multiple source objects to a target, but ONLY * properties whose value is not null, undefined, or NaN. * * Rules: * - Sources are applied left-to-right; later sources override earlier ones. * - Only own enumerable string-keyed properties of ...
for (const source of sources) { for (const key of Object.keys(source)) { const val = (source as any)[key]; if (val !== null && val !== undefined && !(typeof val === 'number' && isNaN(val))) { (target as any)[key] = val; } } } return target;...
} // Basic usage const t = { a: 1, b: 2, c: 3 } as any; const result = compactAssign(t, { a: 10, b: null } as any, { c: undefined, d: 4 } as any); assert.strictEqual(result, t); assert.strictEqual(t.a, 10); assert.strictEqual(t.b, 2); // null skipped assert.strictEqual(t.c, 3); // undefined skipped assert.strictEqua...
// NaN skipping const t2: Record<string, unknown> = { x: 'hello', y: 42 }; compactAssign(t2, { x: NaN, y: 0, z: '' } as any); assert.strictEqual(t2.x, 'hello'); // NaN skipped assert.strictEqual(t2.y, 0); // 0 is valid assert.strictEqual(t2.z, ''); // empty string is valid // Multiple sources override le...
code2NL_NL2code
11
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; type StepFn<T> = (input: T, signal: { aborted: boolean }) => Promise<T>; async function pipeline<T>(input: T, steps: StepFn<T>[]): Promise<{ result: T; completedSteps: number; aborted: boolean }> {
(pipeline as any).doc = 'Execute an array of async steps sequentially, threading each output as the next input. If any step throws, execution halts and the result from the last successful step is returned. Returns an object with result (last successful output or the original input if the first step fails), complete...
const signal = { aborted: false }; let current: T = input; let completed = 0; for (const step of steps) { try { current = await step(current, signal); completed++; } catch { signal.aborted = true; return { result: current, completedSteps: c...
(async () => { await pipeline<number>(0, []); const doc: string = (pipeline as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('sequential') || dl.includes('sequentially')); assert.ok(dl.includes('last successful') || dl.includes('previous result...
code2NL_NL2code
12
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; function deepClone<T>(obj: T, seen?: Map<any, any>): T {
(deepClone as any).doc = 'Recursively deep-clone a value, preserving Date instances as new Date copies and handling circular references by returning the previously cloned reference. Arrays are cloned element-by-element maintaining index order. Only own enumerable properties are cloned for plain objects. Primitives ...
if (obj === null || typeof obj !== 'object') return obj; if (!seen) seen = new Map(); if (seen.has(obj)) return seen.get(obj); if (obj instanceof Date) return new Date(obj.getTime()) as any; if (Array.isArray(obj)) { const arr: any[] = []; seen.set(obj, arr); for (let i = 0; ...
deepClone(42); const doc: string = (deepClone as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('circular') || dl.includes('cycle')); assert.ok(dl.includes('date')); assert.ok(dl.includes('own') || dl.includes('enumerable')); assert.ok(dl.includes('primitive') || dl.in...
code2NL_NL2code
13
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; interface DiffResult<T> { added: { value: T; index: number }[]; removed: { value: T; index: number }[]; kept: { value: T; oldIndex: number; newIndex: number }[]; } function arrayDiff<T>(oldArr: T[], newArr: T[]): DiffResult<T> {
(arrayDiff as any).doc = 'Compute the difference between two arrays using strict equality (===). Returns an object with added (items in newArr not in oldArr, with their newArr index), removed (items in oldArr not in newArr, with their oldArr index), and kept (items present in both, with both old and new indices). E...
const oldUsed = new Array(oldArr.length).fill(false); const newUsed = new Array(newArr.length).fill(false); const kept: { value: T; oldIndex: number; newIndex: number }[] = []; for (let ni = 0; ni < newArr.length; ni++) { for (let oi = 0; oi < oldArr.length; oi++) { if (!oldUsed[oi] ...
arrayDiff([], []); const doc: string = (arrayDiff as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('strict equality') || dl.includes('===')); assert.ok(dl.includes('at most once') || dl.includes('first') || dl.includes('first unmatched')); assert.ok(dl.includes('dupli...
code2NL_NL2code
14
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; interface RetryOpts { maxAttempts: number; baseDelayMs: number; maxDelayMs: number; jitter: boolean; } async function retryWithCeiling<T>(fn: () => Promise<T>, opts: RetryOpts): Promise<{ value: T; attempts: number }> {
(retryWithCeiling as any).doc = 'Retry an async function up to maxAttempts times with exponential backoff capped at maxDelayMs. The delay starts at baseDelayMs and doubles each attempt but never exceeds maxDelayMs. When jitter is true, the actual delay is a random value between 0 and the computed delay. Returns an ...
let delay = opts.baseDelayMs; let lastError: any; for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) { try { const value = await fn(); return { value, attempts: attempt }; } catch (err) { lastError = err; if (attempt < opts.maxAttemp...
let c2 = 0; (async () => { try { await retryWithCeiling(async () => { c2++; if(c2<2) throw new Error('x'); return 1; }, { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 10, jitter: false }); } catch {} const doc: string = (retryWithCeiling as any).doc; assert.ok(typeof doc === 'string'); const dl =...
code2NL_NL2code
15
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; type Schema = { [key: string]: 'string' | 'number' | 'boolean' | Schema }; interface ValidationError { path: string; expected: string; actual: string; } function validateSchema(obj: any, schema: Schema, path: string = ''): ValidationError[] {
(validateSchema as any).doc = 'Validate an object against a nested type schema, collecting all errors rather than failing on the first. Each error includes the dot-separated path to the offending field, the expected type, and the actual type (using typeof). Extra keys in the object that are not in the schema are si...
const errors: ValidationError[] = []; for (const key of Object.keys(schema)) { const fullPath = path ? `${path}.${key}` : key; const expected = schema[key]; const value = obj?.[key]; if (typeof expected === 'object') { if (typeof value !== 'object' || value === null) ...
validateSchema({}, {}); const doc: string = (validateSchema as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('all errors') || dl.includes('collecting') || dl.includes('every error')); assert.ok(dl.includes('dot') || dl.includes('path')); assert.ok(dl.includes('extra')...
code2NL_NL2code
16
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; class EventBus { private _handlers: Map<string, { fn: Function; once: boolean }[]> = new Map(); on(event: string, fn: Function, once: boolean = false): () => void {
(EventBus.prototype.on as any).doc = 'Subscribe fn to event. If once is true, the listener auto-removes after its first invocation. The wildcard event "*" matches all events; wildcard listeners receive the event name as the first argument followed by the original arguments. Returns an unsubscribe function that ...
if (!this._handlers.has(event)) this._handlers.set(event, []); const entry = { fn, once }; this._handlers.get(event)!.push(entry); return () => { const list = this._handlers.get(event); if (list) { const idx = list.indexOf(entry); i...
const bus2 = new EventBus(); bus2.on('x', () => {}); const doc: string = (EventBus.prototype.on as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('wildcard') || dl.includes('*')); assert.ok(dl.includes('event name') || dl.includes('first argument')); assert.ok(dl.inclu...
code2NL_NL2code
17
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; function throttle<A extends any[], R>( fn: (...args: A) => R, intervalMs: number ): { call: (...args: A) => R | undefined; flush: () => R | undefined; pending: () => boolean } {
(throttle as any).doc = 'Create a throttled wrapper that invokes fn at most once per intervalMs milliseconds. The first call executes immediately. Subsequent calls within the interval are suppressed but the last suppressed call is saved and automatically fired when the interval expires (trailing call guarantee). Re...
let lastTime = 0; let timer: ReturnType<typeof setTimeout> | null = null; let savedArgs: A | null = null; let lastResult: R | undefined; function call(...args: A): R | undefined { const now = Date.now(); if (now - lastTime >= intervalMs) { lastTime = now; if ...
throttle(() => {}, 100); const doc: string = (throttle as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('trailing') || dl.includes('last suppressed') || dl.includes('saved')); assert.ok(dl.includes('flush')); assert.ok(dl.includes('pending')); assert.ok(dl.includes('i...
code2NL_NL2code
18
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; class ExpiringMap<K, V> { private _store: Map<K, { value: V; expiresAt: number }> = new Map(); private _defaultTTL: number; constructor(defaultTTLMs: number) { this._defaultTTL = defaultTTLMs; } set(key: K, value: V, ttlMs?: number): void {
(ExpiringMap.prototype.set as any).doc = 'Store a key-value pair with an expiration time. If ttlMs is provided, the entry expires after that many milliseconds from now; otherwise it uses the instance default TTL. Setting an already-existing key overwrites both the value and the expiration time (the old TTL is n...
const ttl = ttlMs !== undefined ? ttlMs : this._defaultTTL; this._store.set(key, { value, expiresAt: Date.now() + ttl }); } get(key: K): V | undefined { const entry = this._store.get(key); if (!entry) return undefined; if (Date.now() >= entry.expiresAt) { thi...
const m2 = new ExpiringMap<string, number>(100000); m2.set('x', 10); const doc: string = (ExpiringMap.prototype.set as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('overwrite') || dl.includes('replace')); assert.ok(dl.includes('lazily') || dl.includes('lazy') || dl.i...
code2NL_NL2code
19
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; // Implement weightedSample according to this specification: // // Select one item from `items` using the corresponding `weights`. // Rules: // 1. Weights are positive numbers (not necessarily summing to 1). // 2. The `rng` parameter is a function returning a float in [0, 1). // 3. Se...
function weightedSample<T>(items: T[], weights: number[], rng: () => number): T | undefined { if (items.length === 0) return undefined; const w = items.map((_, i) => (i < weights.length ? weights[i] : 1)); const total = w.reduce((s, v) => s + v, 0); const threshold = rng() * total; let cum = 0; ...
assert.strictEqual(weightedSample(['a','b','c'], [1, 2, 1], () => 0.0), 'a'); assert.strictEqual(weightedSample(['a','b','c'], [1, 2, 1], () => 0.99), 'c'); assert.strictEqual(weightedSample([], [], () => 0.5), undefined);
// Default weight for missing entries assert.strictEqual(weightedSample(['x','y'], [3], () => 0.0), 'x'); // rng=0.74: threshold=0.74*4=2.96, cum: x=3 > 2.96 → 'x' assert.strictEqual(weightedSample(['x','y'], [3], () => 0.74), 'x'); // rng=0.76: threshold=0.76*4=3.04, cum: x=3, y=4 > 3.04 → 'y' assert.strictEqual(weigh...
code2NL_NL2code
20
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; // Implement parseConfig according to this specification: // // Parse an INI-style config string into a nested object. // Rules: // 1. Lines are separated by '\n'. // 2. Blank lines and lines starting with '#' (after trimming) are ignored. // 3. Section headers look like '[sectionName...
function parseConfig(input: string): Record<string, Record<string, string | number | boolean>> { const res: Record<string, Record<string, any>> = { __global__: {} }, parents: Record<string, string> = {}; let cur = '__global__'; for (const raw of input.split('\n')) { const ln = raw.trim(); if (!ln || ln....
const cfg = parseConfig('[base]\nport = 3000\nhost = localhost\n[dev:base]\ndebug = true\nport = 8080'); assert.strictEqual(cfg.base.port, 3000); assert.strictEqual(cfg.dev.port, 8080); assert.strictEqual(cfg.dev.debug, true); assert.strictEqual(cfg.dev.host, 'localhost');
// Global keys const c1 = parseConfig('globalKey = 42\n[sec]\nfoo = bar'); assert.strictEqual(c1.__global__.globalKey, 42); assert.strictEqual(c1.sec.foo, 'bar'); // Comments and blank lines const c2 = parseConfig('# comment\n\nk = v\n[s]\n# another\nx = 10'); assert.strictEqual(c2.__global__.k, 'v'); assert.strictEqua...
code2NL_NL2code
21
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; type Unsubscribe = () => void; class Observable<T> { private listeners: Array<{ fn: (val: T) => void; once: boolean }> = []; subscribe(fn: (val: T) => void, once: boolean = false): Unsubscribe {
(Observable.prototype.subscribe as any).doc = 'Register a listener that receives emitted values. When once is true, the listener ' + 'auto-removes itself after the first invocation. Returns an idempotent unsubscribe ' + 'function that removes the listener from the internal ar...
const entry = { fn, once }; this.listeners.push(entry); let removed = false; return () => { if (removed) return; removed = true; const idx = this.listeners.indexOf(entry); if (idx >= 0) this.listeners.splice(idx, 1); }; } e...
const obs2 = new Observable<string>(); const seen: string[] = []; const u1 = obs2.subscribe(v => seen.push(v), true); obs2.emit('a'); obs2.emit('b'); assert.deepStrictEqual(seen, ['a']); u1(); u1(); const doc = (Observable.prototype.subscribe as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase()...
code2NL_NL2code
22
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; interface TreeNode<T> { value: T; children: TreeNode<T>[]; } function flattenTree<T>(root: TreeNode<T>, depthFirst: boolean = true): T[] {
(flattenTree as any).doc = 'Flatten a tree into an array using either pre-order depth-first (default) or breadth-first traversal. ' + 'The root value always appears first. Children are visited left-to-right at each level. ' + 'Returns a new array without mutating the tree. Throws TypeError i...
if (root == null) throw new TypeError('root must not be null or undefined'); const result: T[] = []; if (depthFirst) { const stack: TreeNode<T>[] = [root]; while (stack.length > 0) { const node = stack.pop()!; result.push(node.value); for (let i = node.chi...
assert.throws(() => flattenTree(null as any), TypeError); const doc = (flattenTree as any).doc; assert.ok(typeof doc === 'string'); const dl = doc.toLowerCase(); assert.ok(dl.includes('depth-first') || dl.includes('depth first'), 'must mention depth-first'); assert.ok(dl.includes('breadth-first') || dl.includes('breadt...
code2NL_NL2code
23
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; type Transition<S extends string, E extends string> = { from: S; event: E; to: S; guard?: () => boolean; }; class StateMachine<S extends string, E extends string> { private current: S; private transitions: Transition<S, E>[]; private history: Array<{ from: S; event: E...
return 'A typed finite state machine that processes events via guarded transitions. ' + 'The send method finds the first transition matching the current state and event whose guard returns true, ' + 'then updates the state and appends the transition to an internal history log. ' + 'If no mat...
} type S = 'idle' | 'loading' | 'done'; type E = 'fetch' | 'resolve'; const sm = new StateMachine<S, E>('idle', [ { from: 'idle', event: 'fetch', to: 'loading' }, { from: 'loading', event: 'resolve', to: 'done' } ]); assert.strictEqual(sm.send('fetch'), 'loading'); assert.strictEqual(sm.send('resolve'), 'done'...
const desc = describeStateMachine(); assert.ok(typeof desc === 'string'); const dl = desc.toLowerCase(); assert.ok(dl.includes('guard'), 'must mention guards'); assert.ok(dl.includes('first') && dl.includes('matching'), 'must mention first matching transition'); assert.ok(dl.includes('history') || dl.includes('log'), '...
code2NL_NL2code
24
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; function throttle<T extends (...args: any[]) => any>( fn: T, intervalMs: number, options: { leading?: boolean; trailing?: boolean } = {} ): T & { cancel: () => void; doc?: string } {
const result = (function(this: any, ...args: any[]) { // doc set below }) as any; result.doc = 'Throttle a function so it executes at most once per intervalMs milliseconds. ' + 'Leading defaults to true (first call fires immediately); trailing defaults to false. ' + 'When tra...
const leading = options.leading !== false; const trailing = options.trailing === true; let lastCallTime: number | null = null; let timer: ReturnType<typeof setTimeout> | null = null; let lastArgs: any[] | null = null; let lastThis: any = null; const throttled = function(this: any, ...args: ...
const t2 = throttle((x: number) => x, 50); const doc = t2.doc; assert.ok(typeof doc === 'string'); const dl = doc!.toLowerCase(); assert.ok(dl.includes('at most once'), 'must mention at most once'); assert.ok(dl.includes('leading'), 'must mention leading'); assert.ok(dl.includes('trailing'), 'must mention trailing'); a...
code2NL_NL2code
25
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; interface Context { [key: string]: any; } type Middleware = (ctx: Context, next: () => Promise<void>) => Promise<void>; class Pipeline { private stack: Middleware[] = []; use(mw: Middleware): this { this.stack.push(mw); return this; } async run(...
(Pipeline.prototype.run as any).doc = 'Execute the middleware stack in registration order using Koa-style compose. ' + 'Each middleware receives the shared context and an async next function. ' + 'Calling next exactly once invokes the downstream middleware; calling next more ...
let index = -1; const dispatch = async (i: number): Promise<void> => { if (i <= index) throw new Error('next() called multiple times'); index = i; if (i < this.stack.length) { await this.stack[i](ctx, () => dispatch(i + 1)); } }; ...
const p2 = new Pipeline(); p2.use(async (ctx, next) => { ctx.a = 1; }); p2.use(async (ctx, next) => { ctx.b = 2; }); p2.run({}).then(ctx => { assert.strictEqual(ctx.a, 1); assert.strictEqual(ctx.b, undefined); }); const doc = (Pipeline.prototype.run as any).doc; assert.ok(typeof doc === 'string'); const dl = do...
code2NL_NL2code
26
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; class Signal<T> { private _value: T; private _subscribers: Set<() => void> = new Set(); constructor(initial: T) { this._value = initial; } get value(): T { if (Signal._tracking) Signal._tracking.add(this); return this._value; } set value(v: T...
return 'Creates a lazily-evaluated computed value that auto-tracks Signal dependencies via a global tracking set. ' + 'On first access or after any dependency changes, the compute function re-runs and the result is cached. ' + 'Dependencies are re-discovered on each recomputation by intercepting Sig...
} const a = new Signal(2); const b = new Signal(3); const sum = computed(() => a.value + b.value); assert.strictEqual(sum.value, 5); a.value = 10; assert.strictEqual(sum.value, 13);
const desc = describeComputed(); assert.ok(typeof desc === 'string'); const dl = desc.toLowerCase(); assert.ok(dl.includes('lazily') || dl.includes('lazy'), 'must mention lazy evaluation'); assert.ok(dl.includes('auto-track') || dl.includes('auto track') || dl.includes('tracking'), 'must mention auto-tracking'); assert...
code2NL_NL2code
27
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; /** * Parse a simplified INI string into a nested object. * - Sections are denoted by [name] on their own line. * - Key=value pairs are split on the first '=' only; both key and value are trimmed. * - Lines starting with ';' or '#' (after trimming) are comments and skipped. * - B...
const result: Record<string, Record<string, string>> = {}; let currentSection = '__global__'; result[currentSection] = {}; const lines = text.split(/\r?\n/); for (let i = 0; i < lines.length; i++) { const trimmed = lines[i].trim(); if (trimmed === '' || trimmed.startsWith(';') || tri...
} const ini = ` name = app [db] host = localhost port = 5432 ; comment [db] port = 3306 `; const parsed = parseINI(ini); assert.strictEqual(parsed['__global__']['name'], 'app'); assert.strictEqual(parsed['db']['host'], 'localhost'); assert.strictEqual(parsed['db']['port'], '3306');
const r2 = parseINI('# comment\n a = b = c \n[s1]\nk = v'); assert.strictEqual(r2['__global__']['a'], 'b = c'); assert.strictEqual(r2['s1']['k'], 'v'); let threw = false; try { parseINI('[bad section\nk=v'); } catch(e: any) { threw = true; assert.ok(e instanceof SyntaxError); assert.ok(e.message.includes(...
code2NL_NL2code
28
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; /** * Perform a stable topological sort on a directed acyclic graph. * - `graph` maps each node to its list of dependencies (nodes it depends on). * - Nodes not in graph keys but appearing as dependencies are treated as having no deps. * - When multiple nodes are ready, they are e...
const allNodes = new Set<string>(); const inDegree: Record<string, number> = {}; const adj: Record<string, string[]> = {}; for (const [node, deps] of Object.entries(graph)) { allNodes.add(node); for (const d of deps) allNodes.add(d); } for (const n of allNodes) { inDegree[n] = 0;...
} const sorted = topoSort({ c: ['a', 'b'], b: ['a'], a: [] }); assert.deepStrictEqual(sorted, ['a', 'b', 'c']);
const r2 = topoSort({ x: ['y'], y: [], z: ['y'] }); assert.strictEqual(r2.indexOf('y'), 0); assert.ok(r2.indexOf('x') > r2.indexOf('y')); assert.ok(r2.indexOf('z') > r2.indexOf('y')); assert.strictEqual(r2[1], 'x'); assert.strictEqual(r2[2], 'z'); let cycleThrew = false; try { topoSort({ a: ['b'], b: ['a'] }); } catch...
code2NL_NL2code
29
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; interface Token { type: 'string' | 'number' | 'ident' | 'symbol'; value: string; } /** * Tokenize an expression string into an array of tokens. * Rules: * - Whitespace is skipped (spaces and tabs only). * - A string literal starts and ends with a double quote. Backslash e...
const tokens: Token[] = []; let i = 0; while (i < input.length) { if (input[i] === ' ' || input[i] === '\t') { i++; continue; } if (input[i] === '"') { let s = ''; i++; while (i < input.length && input[i] !== '"') { if (input[i] === '\\') {...
} const toks = tokenize('foo + 3.14'); assert.strictEqual(toks.length, 3); assert.deepStrictEqual(toks[0], { type: 'ident', value: 'foo' }); assert.deepStrictEqual(toks[1], { type: 'symbol', value: '+' }); assert.deepStrictEqual(toks[2], { type: 'number', value: '3.14' });
const t2 = tokenize('"he\\\\llo" 42'); assert.strictEqual(t2.length, 2); assert.deepStrictEqual(t2[0], { type: 'string', value: 'he\\llo' }); assert.deepStrictEqual(t2[1], { type: 'number', value: '42' }); const t3 = tokenize('_x2 ()'); assert.strictEqual(t3.length, 3); assert.deepStrictEqual(t3[0], { type: 'ident', v...
code2NL_NL2code
30
devbench-code2NL-NL2code
typescript
import * as assert from 'assert'; interface DiffHunk { type: 'equal' | 'insert' | 'delete'; lines: string[]; } /** * Compute a line-level diff between two strings. * - Split both strings on '\n' to get line arrays. * - Use longest common subsequence (LCS) to align equal lines. * - Return an array of DiffH...
const linesA = a.split('\n'); const linesB = b.split('\n'); const m = linesA.length, n = linesB.length; const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) dp[i][j] = linesA[i-1] === linesB[j-...
} const d1 = lineDiff('a\nb\nc', 'a\nc'); assert.deepStrictEqual(d1, [ { type: 'equal', lines: ['a'] }, { type: 'delete', lines: ['b'] }, { type: 'equal', lines: ['c'] } ]);
const d2 = lineDiff('x', 'y'); assert.strictEqual(d2.length, 2); assert.deepStrictEqual(d2[0], { type: 'delete', lines: ['x'] }); assert.deepStrictEqual(d2[1], { type: 'insert', lines: ['y'] }); const d3 = lineDiff('a\nb', 'a\nb\nc'); assert.deepStrictEqual(d3, [ { type: 'equal', lines: ['a', 'b'] }, { type: '...
code2NL_NL2code
31
devbench-code2NL-NL2code
typescript
function memoizeWithTTL<A extends object, R>( fn: (arg: A) => R, ttlMs: number ): (arg: A) => R { const cache = new WeakMap<A, { value: R; expiry: number }>(); return (arg: A): R => { const now = Date.now(); if (cache.has(arg)) { const entry = cache.get(arg)!; if ...
memoizeWithTTL.doc = 'Creates a memoized version of a function that caches results in a WeakMap, constraining the argument type A to extend object so keys can be garbage-collected. Each cache entry stores both the computed value and an expiry timestamp calculated as Date.now() plus ttlMs. On subsequent calls, returns t...
// Basic functionality const fn1 = (obj: { n: number }) => obj.n * 2; const memoized1 = memoizeWithTTL(fn1, 10000); const arg1 = { n: 5 }; console.assert(memoized1(arg1) === 10); console.assert(memoized1(arg1) === 10); // cached console.log('Task 31 suffix passed');
const doc31 = (memoizeWithTTL as any).doc as string; console.assert(doc31.includes('WeakMap'), 'must mention WeakMap'); console.assert(doc31.includes('garbage-collect') || doc31.includes('garbage collect'), 'must mention garbage collection'); console.assert(doc31.includes('expiry') || doc31.includes('expiration'), 'mus...
code2NL_NL2code
32
devbench-code2NL-NL2code
typescript
type Shape = | { kind: 'circle'; radius: number } | { kind: 'rect'; width: number; height: number } | { kind: 'triangle'; base: number; height: number }; function totalArea(shapes: Shape[]): number { let total = 0; for (const s of shapes) { switch (s.kind) { case 'circle': ...
totalArea.doc = 'Computes the sum of areas for an array of discriminated union Shape values by switching on the kind discriminant. For circle uses PI*r^2, for rect uses width*height, for triangle uses 0.5*base*height. Accumulates into a mutable total variable using a for-of loop. Includes an exhaustiveness check via a ...
const shapes: Shape[] = [ { kind: 'circle', radius: 1 }, { kind: 'rect', width: 2, height: 3 }, { kind: 'triangle', base: 4, height: 5 }, ]; const result32 = totalArea(shapes); console.assert(Math.abs(result32 - (Math.PI + 6 + 10)) < 0.001); console.log('Task 32 suffix passed');
const doc32 = (totalArea as any).doc as string; console.assert(doc32.includes('discriminat') || doc32.includes('kind'), 'must mention discriminant or kind'); console.assert(doc32.includes('never'), 'must mention never type for exhaustiveness'); console.assert(doc32.includes('exhaustive') || doc32.includes('exhaustivene...
code2NL_NL2code
33
devbench-code2NL-NL2code
typescript
interface Config { readonly host: string; readonly port: number; readonly retries: number; readonly timeout: number; } class ConfigBuilder { private _host: string = 'localhost'; private _port: number = 8080; private _retries: number = 3; private _timeout: number = 5000; host(h: str...
(ConfigBuilder.prototype as any).doc = 'A fluent builder for Config objects where each setter method (host, port, retries, timeout) mutates private state and returns this for method chaining. Private fields have defaults: localhost, 8080, 3, and 5000. The build() method creates a new Config object and freezes it with O...
const cfg = new ConfigBuilder() .host('example.com') .port(443) .retries(5) .build(); console.assert(cfg.host === 'example.com'); console.assert(cfg.port === 443); console.assert(cfg.retries === 5); console.assert(cfg.timeout === 5000); console.assert(Object.isFrozen(cfg)); console.log('Task 33 suffix p...
const doc33 = (ConfigBuilder.prototype as any).doc as string; console.assert(doc33.includes('Object.freeze') || doc33.includes('freeze'), 'must mention Object.freeze'); console.assert(doc33.includes('immutable') || doc33.includes('frozen'), 'must mention immutability'); console.assert(doc33.includes('runtime'), 'must m...
code2NL_NL2code
34
devbench-code2NL-NL2code
typescript
function createRetrier(maxAttempts: number, baseDelayMs: number) { let attemptCount = 0; let lastDelay = 0; return { async attempt<T>(fn: () => Promise<T>): Promise<T> { attemptCount++; try { const result = await fn(); attemptCount = 0; ...
(createRetrier as any).doc = 'Factory that returns a stateful retrier object with closure-captured attemptCount and lastDelay variables. The attempt() method is generic over T and accepts an async function. On success, it resets both counters to zero and returns the result. On failure, if attemptCount reaches maxAttemp...
const retrier = createRetrier(3, 100); let callCount = 0; const succeedOnThird = async () => { callCount++; if (callCount < 3) throw new Error('fail'); return 'ok'; }; retrier.attempt(succeedOnThird).then(result => { console.assert(result === 'ok'); console.assert(retrier.getAttemptCount() === 0); /...
const doc34 = (createRetrier as any).doc as string; console.assert(doc34.includes('closure') || doc34.includes('captured'), 'must mention closure-captured state'); console.assert(doc34.includes('attemptCount') || doc34.includes('attempt count'), 'must mention attemptCount'); console.assert(doc34.includes('exponential')...
code2NL_NL2code
35
devbench-code2NL-NL2code
typescript
class TypedEmitter<Events extends Record<string, unknown[]>> { private handlers = new Map<keyof Events, Set<Function>>(); on<K extends keyof Events>(event: K, handler: (...args: Events[K]) => void): () => void { if (!this.handlers.has(event)) { this.handlers.set(event, new Set()); }...
(TypedEmitter.prototype as any).doc = 'A generic event emitter parameterized by an Events record mapping event names to argument tuples, providing compile-time type safety for event payloads. on() registers a handler in a Map<keyof Events, Set<Function>> and returns an unsubscribe function that deletes the handler from...
type MyEvents = { data: [number, string]; close: []; }; const emitter = new TypedEmitter<MyEvents>(); let dataCalls = 0; const unsub = emitter.on('data', (n, s) => { dataCalls++; }); emitter.emit('data', 42, 'hello'); console.assert(dataCalls === 1); unsub(); emitter.emit('data', 99, 'world'); console.assert(da...
const doc35 = (TypedEmitter.prototype as any).doc as string; console.assert(doc35.includes('Map') && doc35.includes('Set'), 'must mention Map and Set storage'); console.assert(doc35.includes('unsubscribe') || doc35.includes('unsub') || doc35.includes('delete'), 'must mention unsubscribe/delete'); console.assert(doc35.i...
code2NL_NL2code
36
devbench-code2NL-NL2code
typescript
type Context = { path: string; headers: Record<string, string>; body: string; status: number }; type Middleware = (ctx: Context, next: () => Promise<void>) => Promise<void>; function compose(middlewares: Middleware[]): (ctx: Context) => Promise<void> { return function(ctx: Context) { let index = -1; ...
(compose as any).doc = 'Composes an array of async middleware functions into a single handler using an index-tracking dispatch mechanism. Each middleware receives a shared mutable Context and a next function that advances to the next middleware via dispatch(i+1). The dispatch function guards against calling next() mult...
const log: string[] = []; const mw1: Middleware = async (ctx, next) => { log.push('a-before'); await next(); log.push('a-after'); }; const mw2: Middleware = async (ctx, next) => { log.push('b-before'); ctx.status = 200; await next(); log.push('b-after'); }; const mw3: Middleware = async (ctx, next) => { log.push('c'); ...
const doc36 = (compose as any).doc as string; console.assert(doc36.includes('dispatch') || doc36.includes('index'), 'must mention dispatch/index mechanism'); console.assert(doc36.includes('next()') || doc36.includes('next function'), 'must mention next'); console.assert(doc36.includes('multiple times') || doc36.include...
code2NL_NL2code
37
devbench-code2NL-NL2code
typescript
class LazySeq<T> { constructor(private generator: () => Generator<T>) {} static from<U>(arr: U[]): LazySeq<U> { return new LazySeq(function* () { yield* arr; }); } map<U>(fn: (item: T) => U): LazySeq<U> { const gen = this.generator; return new LazySeq(function* () { ...
(LazySeq.prototype as any).doc = 'A lazy sequence wrapper that stores a generator factory function and defers all computation until terminal operations (take or toArray) are called. from() creates a LazySeq by wrapping an array in a generator using yield*. map() and filter() return new LazySeq instances with composed g...
const seq = LazySeq.from([1, 2, 3, 4, 5]) .map(x => x * 10) .filter(x => x > 20); console.assert(JSON.stringify(seq.take(2)) === '[30,40]'); console.assert(JSON.stringify(seq.toArray()) === '[30,40,50]'); // Replayable console.assert(JSON.stringify(seq.toArray()) === '[30,40,50]'); console.log('Task 37 suffix p...
const doc37 = (LazySeq.prototype as any).doc as string; console.assert(doc37.includes('generator') || doc37.includes('Generator'), 'must mention generator'); console.assert(doc37.includes('lazy') || doc37.includes('defer'), 'must mention lazy/deferred evaluation'); console.assert(doc37.includes('factory') || doc37.incl...
code2NL_NL2code
38
devbench-code2NL-NL2code
typescript
// Implement deepPartialEqual(obj, partial) that returns true if every // property in 'partial' exists in 'obj' with the same value, recursively. // Properties in 'obj' that are NOT in 'partial' are ignored. // // Rules: // 1. For primitives (non-objects, null): use strict equality (===) // 2. For arrays: partial must ...
function deepPartialEqual(obj: any, partial: any): boolean { if (partial === null || partial === undefined) return obj === partial; if (typeof partial !== 'object') return obj === partial; if (Array.isArray(partial)) { if (!Array.isArray(obj) || obj.length !== partial.length) return false; r...
// Basic match console.assert(deepPartialEqual({ a: 1, b: 2, c: 3 }, { a: 1, c: 3 }) === true); // Nested match console.assert(deepPartialEqual({ a: { b: { c: 1 } } }, { a: { b: { c: 1 } } }) === true); // Extra keys in obj OK console.assert(deepPartialEqual({ a: 1, b: 2 }, { a: 1 }) === true); // Missing key in obj co...
// Empty partial matches anything console.assert(deepPartialEqual({ a: 1 }, {}) === true); console.assert(deepPartialEqual({}, {}) === true); // Null/undefined strict equality console.assert(deepPartialEqual(null, null) === true); console.assert(deepPartialEqual(undefined, undefined) === true); console.assert(deepParti...
code2NL_NL2code
39
devbench-code2NL-NL2code
typescript
// Implement topologicalSort(edges) that returns a valid topological // ordering of nodes, or throws an Error('cycle detected') if one exists. // // edges is an array of [from, to] pairs representing a directed graph. // ALL nodes mentioned in edges must appear in the output. // // Rules: // 1. If multiple valid orderi...
function topologicalSort(edges: [string, string][]): string[] { const graph = new Map<string, Set<string>>(); const indegree = new Map<string, number>(); for (const [from, to] of edges) { if (!graph.has(from)) { graph.set(from, new Set()); indegree.set(from, indegree.get(from) ?? 0); } if (!...
// Simple chain const r1 = topologicalSort([['a', 'b'], ['b', 'c']]); console.assert(JSON.stringify(r1) === '["a","b","c"]'); // Multiple valid orderings — prefer lex smallest const r2 = topologicalSort([['c', 'd'], ['a', 'b']]); console.assert(r2[0] === 'a' || r2[0] === 'c'); // both have indegree 0 console.assert(r2...
// Self-loop is a cycle let threw2 = false; try { topologicalSort([['a', 'a']]); } catch (e: any) { threw2 = true; console.assert(e.message === 'cycle detected'); } console.assert(threw2, 'self-loop must be detected as cycle'); // Lex order when all independent const r3 = topologicalSort([['c', 'd'], ['a', 'b'], ['e',...
code2NL_NL2code
40
devbench-code2NL-NL2code
typescript
// Implement deepClone(value) that creates a deep copy of the input. // // Rules: // 1. Primitives (number, string, boolean, null, undefined): return as-is // 2. Date objects: return a new Date with the same time value // 3. RegExp objects: return a new RegExp with the same pattern and flags // 4. Arrays: recursively c...
function deepClone<T>(value: T, seen = new Map<any, any>()): T { if (value === null || typeof value !== 'object') return value; if (seen.has(value)) return seen.get(value); if (value instanceof Date) return new Date(value.getTime()) as any; if (value instanceof RegExp) return new RegExp(value.source, va...
// Basic deep clone const orig = { a: 1, b: { c: [2, 3] }, d: new Date('2024-01-01'), e: /test/gi }; const cloned = deepClone(orig); console.assert(cloned.a === 1); console.assert(cloned.b.c[0] === 2); console.assert(cloned.b !== orig.b); console.assert(cloned.b.c !== orig.b.c); console.assert(cloned.d instanceof Date)...
// Primitives pass through console.assert(deepClone(42) === 42); console.assert(deepClone('hi') === 'hi'); console.assert(deepClone(null) === null); console.assert(deepClone(undefined) === undefined); console.assert(deepClone(true) === true); // Nested arrays const arr = [[1, 2], [3, [4, 5]]]; const arrClone = deepClo...
code2NL_NL2code
41
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; class RingBuffer<T> { private buf: (T | undefined)[]; private head: number = 0; private count: number = 0; private cap: number; constructor(capacity: number) { this.cap = capacity; this.buf = new Array(capacity).fill(undefined); } ...
(RingBuffer as any).doc = 'A fixed-capacity circular buffer that overwrites the oldest element when full. push(item) appends to the logical end and returns the evicted element if the buffer was at capacity, or undefined if no eviction occurred. shift() removes and returns the oldest element, or undefined if the buffer ...
const rb = new RingBuffer<number>(3); assert.strictEqual(rb.push(1), undefined); assert.strictEqual(rb.push(2), undefined); assert.strictEqual(rb.push(3), undefined); assert.strictEqual(rb.size, 3); // Overwrite oldest const evicted = rb.push(4); assert.strictEqual(evicted, 1); assert.deepStrictEqual(rb.toArray(), [2,...
const doc41 = (RingBuffer as any).doc; assert.ok(doc41.includes('fixed-capacity') || doc41.includes('fixed capacity'), 'must mention fixed capacity'); assert.ok(doc41.includes('oldest') || doc41.includes('FIFO'), 'must mention overwrites oldest'); assert.ok(doc41.includes('evict') || doc41.includes('overwrite'), 'must ...
code2NL_NL2code
42
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; interface TrieNode { children: Map<string, TrieNode>; prefixCount: number; isEnd: boolean; } class CountingTrie { private root: TrieNode; constructor() { this.root = { children: new Map(), prefixCount: 0, isEnd: false }; } insert(word: s...
(CountingTrie as any).doc = 'A trie (prefix tree) that tracks how many inserted words pass through each node via a prefixCount field. insert(word) traverses or creates nodes for each character, incrementing prefixCount at every visited node and marking the final node as an end-of-word. search(word) returns a boolean in...
const trie = new CountingTrie(); trie.insert('apple'); trie.insert('app'); trie.insert('application'); assert.strictEqual(trie.search('app'), true); assert.strictEqual(trie.search('ap'), false); assert.strictEqual(trie.startsWith('app'), 3); assert.strictEqual(trie.startsWith('appl'), 2); console.log('Task 42 suffix ...
const doc42 = (CountingTrie as any).doc; assert.ok(doc42.includes('prefixCount') || doc42.includes('prefix count'), 'must mention prefixCount'); assert.ok(doc42.includes('increment') || doc42.includes('incr'), 'must mention incrementing'); assert.ok(doc42.includes('boolean') || doc42.includes('exact-match') || doc42.in...
code2NL_NL2code
43
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; interface TaggedInterval { start: number; end: number; tags: string[]; } /** * Merge overlapping or adjacent tagged intervals. * Two intervals overlap if one's start is <= the other's end. * When merging, the resulting interval's start is the minimum start, *...
if (intervals.length === 0) return []; const sorted = [...intervals].sort((a, b) => a.start - b.start); const result: TaggedInterval[] = [{ ...sorted[0], tags: [...sorted[0].tags] }]; for (let i = 1; i < sorted.length; i++) { const last = result[result.length - 1]; if (sorted[i].start <=...
} // Basic merge const intervals1: TaggedInterval[] = [ { start: 1, end: 3, tags: ['a', 'b'] }, { start: 2, end: 5, tags: ['b', 'c'] }, { start: 7, end: 9, tags: ['d'] } ]; const merged1 = mergeTaggedIntervals(intervals1); assert.strictEqual(merged1.length, 2); assert.strictEqual(merged1[0].start, 1); asse...
// Empty input assert.deepStrictEqual(mergeTaggedIntervals([]), []); // Unsorted input const intervals2: TaggedInterval[] = [ { start: 5, end: 8, tags: ['x'] }, { start: 1, end: 4, tags: ['y'] }, { start: 3, end: 6, tags: ['z'] } ]; const merged2 = mergeTaggedIntervals(intervals2); assert.strictEqual(merge...
code2NL_NL2code
44
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; type TopoResult = { sorted: string[] | null; cycle: string[] | null; }; function topoSort(edges: [string, string][]): TopoResult { const graph = new Map<string, string[]>(); const inDeg = new Map<string, number>(); const allNodes = new Set<string>(); ...
(topoSort as any).doc = 'Performs topological sorting on a directed graph specified as an array of [source, target] edge pairs. Uses Kahn\'s algorithm with an alphabetically-sorted queue to produce a deterministic ordering when multiple nodes have equal in-degree. Returns an object { sorted, cycle } where exactly one f...
// Acyclic graph const result1 = topoSort([['a', 'b'], ['b', 'c'], ['a', 'c']]); assert.ok(result1.sorted !== null); assert.strictEqual(result1.cycle, null); assert.ok(result1.sorted!.indexOf('a') < result1.sorted!.indexOf('b')); assert.ok(result1.sorted!.indexOf('b') < result1.sorted!.indexOf('c')); // Cyclic graph c...
const doc44 = (topoSort as any).doc; assert.ok(doc44.includes('Kahn') || doc44.includes('kahn'), 'must mention Kahn\'s algorithm'); assert.ok(doc44.includes('alphabetical') || doc44.includes('deterministic'), 'must mention deterministic ordering'); assert.ok(doc44.includes('cycle') && (doc44.includes('sequence') || doc...
code2NL_NL2code
45
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; /** * Deep-clone any JSON-compatible value (objects, arrays, primitives, null). * Must handle circular references: if an object refers back to an ancestor, * the clone must mirror that circular structure rather than throwing or * producing infinite recursion. * * Implem...
const seen = new Map<any, any>(); function clone(val: any): any { if (val === null || typeof val !== 'object') return val; if (seen.has(val)) return seen.get(val); if (Array.isArray(val)) { const arr: any[] = []; seen.set(val, arr); for (const item o...
} // Basic deep clone const orig = { a: 1, b: { c: [2, 3] } }; const cloned = deepClone(orig); assert.deepStrictEqual(cloned, orig); cloned.b.c.push(4); assert.strictEqual(orig.b.c.length, 2); // original unchanged (only [2, 3]) // Circular reference const circular: any = { name: 'root' }; circular.self = circular; c...
// Array with circular ref const arr: any[] = [1, 2]; arr.push(arr); const clonedArr = deepClone(arr); assert.strictEqual(clonedArr[0], 1); assert.strictEqual(clonedArr[1], 2); assert.strictEqual(clonedArr[2], clonedArr); // circular preserved assert.notStrictEqual(clonedArr, arr); // Nested circular const a: any = { ...
code2NL_NL2code
46
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; interface CSVOptions { delimiter?: string; rowSeparator?: string; } function parseCSV(input: string, options: CSVOptions = {}): string[][] { const delim = options.delimiter ?? ','; const rowSep = options.rowSeparator ?? '\n'; const rows: string[][] = []; ...
(parseCSV as any).doc = 'Parses a CSV string into a 2D array of strings (string[][]). Supports quoted fields delimited by double-quote characters; within a quoted field, a literal double-quote is represented by two consecutive double-quotes (RFC 4180 escaped quoting), NOT backslash escaping. Unquoted fields are trimmed...
// Basic CSV const csv1 = 'a, b ,c\n1, 2 ,3'; const parsed1 = parseCSV(csv1); assert.deepStrictEqual(parsed1, [['a', 'b', 'c'], ['1', '2', '3']]); // trimmed // Quoted fields with spaces preserved const csv2 = '"hello world", test ," spaced "'; const parsed2 = parseCSV(csv2); assert.strictEqual(parsed2[0][0], 'hel...
const doc46 = (parseCSV as any).doc; assert.ok(doc46.includes('double-quote') || doc46.includes('doubled') || doc46.includes('two consecutive'), 'must describe quote escaping'); assert.ok(!doc46.includes('backslash') || doc46.includes('NOT backslash'), 'must clarify no backslash escaping'); assert.ok(doc46.includes('tr...
code2NL_NL2code
47
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; interface RateLimitResult { allowed: boolean; retryAfter: number; // ms to wait; 0 if allowed } /** * Create a sliding-window rate limiter for a given resource. * * - maxRequests: maximum requests allowed in the window * - windowMs: the sliding window duration in...
const timestamps: number[] = []; const burstWindowMs = 100; return { tryAcquire(): RateLimitResult { const now = Date.now(); // Remove expired timestamps while (timestamps.length > 0 && timestamps[0] <= now - windowMs) { timestamps.shift(); ...
} // Basic rate limiting const limiter = createRateLimiter(3, 1000, 1); assert.deepStrictEqual(limiter.tryAcquire(), { allowed: true, retryAfter: 0 }); assert.deepStrictEqual(limiter.tryAcquire(), { allowed: true, retryAfter: 0 }); assert.deepStrictEqual(limiter.tryAcquire(), { allowed: true, retryAfter: 0 }); const d...
// Burst multiplier = 2: allows 6 in burst window, but only 3 in full window const burstLimiter = createRateLimiter(3, 1000, 2); // Within burst window (synchronous = same ms), can do up to 6 assert.strictEqual(burstLimiter.tryAcquire().allowed, true); assert.strictEqual(burstLimiter.tryAcquire().allowed, true); assert...
code2NL_NL2code
48
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; function jsonPath(obj: any, path: string): any[] { const results: any[] = []; function evaluate(current: any, tokens: string[]): void { if (tokens.length === 0) { results.push(current); return; } if (current === null ||...
(jsonPath as any).doc = 'Evaluates a JSONPath-like expression against a JavaScript object and returns an array of all matching values. Supports four access modes: (1) dot-notation property access (e.g., "$.foo.bar"), (2) bracket notation for array indices with integer keys (e.g., "[0]") and quoted property names (e.g.,...
const data = { store: { books: [ { title: 'A', price: 10 }, { title: 'B', price: 20 }, { title: 'C', price: 15 } ], name: 'TestStore' } }; // Dot notation assert.deepStrictEqual(jsonPath(data, '$.store.name'), ['TestStore']); // Array index assert.de...
const doc48 = (jsonPath as any).doc; assert.ok(doc48.includes('dot-notation') || doc48.includes('dot notation') || doc48.includes('property access'), 'must mention dot notation'); assert.ok(doc48.includes('bracket') || doc48.includes('array ind'), 'must mention bracket notation'); assert.ok(doc48.includes('wildcard') |...
code2NL_NL2code
49
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; interface Observer<T> { next: (value: T) => void; error: (err: Error) => void; complete: () => void; } type Unsubscribe = () => void; /** * A minimal Observable class with three operators: map, filter, take. * * Constructor takes a subscribe function that rec...
map<U>(fn: (value: T) => U): Observable<U> { return new Observable<U>((obs) => this.subscribe({ next: (v) => { try { obs.next(fn(v)); } catch (e) { obs.error(e as Error); } }, error: (e) => obs.error(e), complete: () => obs.complete() })); } filter(predicate: (value: ...
} // Test map const values: number[] = []; const source = new Observable<number>((obs) => { obs.next(1); obs.next(2); obs.next(3); obs.complete(); }); source.map(x => x * 10).subscribe({ next: (v) => values.push(v) }); assert.deepStrictEqual(values, [10, 20, 30]); // Test filter const evens: number[] = []; source...
// take calls complete and stops const items: number[] = []; let compCount = 0; const infinite = new Observable<number>((obs) => { let i = 0; const id = setInterval(() => obs.next(i++), 1); return () => clearInterval(id); }); // Synchronous source for reliable testing const syncSource = new Observable<numb...
code2NL_NL2code
50
devbench-code2NL-NL2code
typescript
import { strict as assert } from 'assert'; type SchemaType = | { kind: 'string' } | { kind: 'number' } | { kind: 'boolean' } | { kind: 'array'; items: SchemaType } | { kind: 'object'; properties: Record<string, SchemaType>; required?: string[] } | { kind: 'union'; variants: SchemaType[] }; int...
(validateSchema as any).doc = 'Recursively validates a JavaScript value against a declarative schema and returns an array of ValidationError objects, each containing a JSONPath-style path string (e.g., "$.foo[0].bar"), the expected type, and the actual type found. Supports six schema kinds: \'string\', \'number\' (reje...
// Valid object const schema: SchemaType = { kind: 'object', properties: { name: { kind: 'string' }, age: { kind: 'number' }, active: { kind: 'boolean' } }, required: ['name', 'age'] }; const errs1 = validateSchema({ name: 'Alice', age: 30 }, schema); assert.strictEqual(errs1.le...
const doc50 = (validateSchema as any).doc; assert.ok(doc50.includes('recursive') || doc50.includes('Recursive'), 'must mention recursive validation'); assert.ok(doc50.includes('NaN') || doc50.includes('nan'), 'must mention NaN rejection'); assert.ok(doc50.includes('JSONPath') || doc50.includes('path') || doc50.includes...
code2NL_NL2code
1
devbench-low-context
typescript
const STANDARD58: string = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; const REVERSED58: string = STANDARD58.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count: number = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function base58Encode(data: string | Buffer, alphabet: string = REVERSED58): string { const buf: Buffer = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n: bigint = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base: bigint = BigInt(alphabet.length); const out: st...
import * as assert from 'assert'; assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2); assert.strictEqual(base58Encode(Buffer.from('abc')), 'SHoR'); assert.notStrictEqual(base58Encode(Buffer.from('abc')), 'ZiCa'); assert.strictEqual(base58Encode(Buffer.from('abc'), STANDARD58), 'ZiCa'); assert.stri...
assert.strictEqual(base58Encode(Buffer.from([])), ''); assert.strictEqual(base58Encode(Buffer.from([0])), 'z'); assert.strictEqual(base58Encode('abc'), 'SHoR'); assert.strictEqual(base58Encode(Buffer.from('hello')), 'oDsMWSK'); assert.strictEqual(base58Encode(Buffer.from('hello'), STANDARD58), 'Cn8eVZg'); assert.strict...
low_context
2
devbench-low-context
typescript
const STANDARD62: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; const REVERSED62: string = STANDARD62.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count: number = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function base62Encode(data: string | Buffer, alphabet: string = REVERSED62): string { const buf: Buffer = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n: bigint = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base: bigint = BigInt(alphabet.length); const out: st...
import * as assert from 'assert'; assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2); assert.strictEqual(base62Encode(Buffer.from('abc')), 'ZDhc'); assert.notStrictEqual(base62Encode(Buffer.from('abc')), 'QmIN'); assert.strictEqual(base62Encode(Buffer.from('abc'), STANDARD62), 'QmIN'); assert.stri...
assert.strictEqual(base62Encode(Buffer.from([])), ''); assert.strictEqual(base62Encode(Buffer.from([0])), 'z'); assert.strictEqual(base62Encode('abc'), 'ZDhc'); assert.strictEqual(base62Encode(Buffer.from('hello')), 's6Zeki0'); assert.strictEqual(base62Encode(Buffer.from('hello'), STANDARD62), '7tQLFHz'); assert.strict...
low_context
3
devbench-low-context
typescript
const STANDARD36: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const REVERSED36: string = STANDARD36.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count: number = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function base36Encode(data: string | Buffer, alphabet: string = REVERSED36): string { const buf: Buffer = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n: bigint = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base: bigint = BigInt(alphabet.length); const out: st...
import * as assert from 'assert'; assert.strictEqual(leadingZeroBytes(Buffer.from([0, 97, 98, 99])), 1); assert.strictEqual(base36Encode(Buffer.from('abc')), 'W77H8'); assert.notStrictEqual(base36Encode(Buffer.from('abc')), '3SSIR'); assert.strictEqual(base36Encode(Buffer.from('abc'), STANDARD36), '3SSIR'); assert.stri...
assert.strictEqual(base36Encode(Buffer.from([])), ''); assert.strictEqual(base36Encode(Buffer.from([0])), 'Z'); assert.strictEqual(base36Encode('abc'), 'W77H8'); assert.strictEqual(base36Encode(Buffer.from('hello')), 'UA0N705S'); assert.strictEqual(base36Encode(Buffer.from('hello'), STANDARD36), '5PZCSZU7'); assert.str...
low_context
4
devbench-low-context
typescript
const STANDARD32: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; const REVERSED32: string = STANDARD32.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count: number = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function base32Encode(data: string | Buffer, alphabet: string = REVERSED32): string { const buf: Buffer = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n: bigint = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base: bigint = BigInt(alphabet.length); const out: st...
import * as assert from 'assert'; assert.strictEqual(leadingZeroBytes(Buffer.from([0, 97, 98, 99])), 1); assert.strictEqual(base32Encode(Buffer.from('abc')), 'Z5HM4'); assert.notStrictEqual(base32Encode(Buffer.from('abc')), 'GCYTD'); assert.strictEqual(base32Encode(Buffer.from('abc'), STANDARD32), 'GCYTD'); assert.stri...
assert.strictEqual(base32Encode(Buffer.from([])), ''); assert.strictEqual(base32Encode(Buffer.from([0])), '7'); assert.strictEqual(base32Encode('abc'), 'Z5HM4'); assert.strictEqual(base32Encode(Buffer.from('hello')), 'S6NJHE4Q'); assert.strictEqual(base32Encode(Buffer.from('hello'), STANDARD32), 'NBSWY3DP'); assert.str...
low_context
5
devbench-low-context
typescript
const STANDARD16: string = '0123456789ABCDEF'; const REVERSED16: string = STANDARD16.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function base16Encode(data: string | Buffer, alphabet: string = REVERSED16): string { const buf = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base = BigInt(alphabet.length); const out: string[] = []; while (...
const assert = require('assert'); const r5 = base16Encode(Buffer.from('abc')); assert.strictEqual(r5, '9E9D9C'); assert.notStrictEqual(r5, '616263'); assert.strictEqual(base16Encode(Buffer.from('abc'), STANDARD16), '616263'); assert.strictEqual(base16Encode(Buffer.from([0, 0, 1])), 'FFE');
assert.strictEqual(base16Encode(Buffer.from([])), ''); assert.strictEqual(base16Encode(Buffer.from([0])), 'F'); assert.strictEqual(base16Encode('abc'), '9E9D9C'); assert.strictEqual(base16Encode(Buffer.from('hello')), '979A939390'); assert.strictEqual(base16Encode(Buffer.from('hello'), STANDARD16), '68656C6C6F'); asser...
low_context
6
devbench-low-context
typescript
const STANDARD8: string = '01234567'; const REVERSED8: string = STANDARD8.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function octalEncode(data: string | Buffer, alphabet: string = REVERSED8): string { const buf = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base = BigInt(alphabet.length); const out: string[] = []; while (n ...
const assert = require('assert'); const r6 = octalEncode(Buffer.from('A')); assert.strictEqual(r6, '676'); assert.notStrictEqual(r6, '101'); assert.strictEqual(octalEncode(Buffer.from('A'), STANDARD8), '101'); assert.strictEqual(octalEncode(Buffer.from([0, 0, 1])), '776');
assert.strictEqual(octalEncode(Buffer.from([])), ''); assert.strictEqual(octalEncode(Buffer.from([0])), '7'); assert.strictEqual(octalEncode('A'), '676'); assert.strictEqual(octalEncode(Buffer.from('abc')), '47516634'); assert.strictEqual(octalEncode(Buffer.from('hello')), '1363244711620'); assert.strictEqual(octalEnco...
low_context
7
devbench-low-context
typescript
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
function tryCatch<T>(fn: () => T): Result<T, Error> { try { return { ok: true, value: fn() }; } catch (e) { return { ok: false, error: e instanceof Error ? e : new Error(String(e)) }; } } function mapResult<T, U, E>(r: Result<T, E>, fn: (v: T) => U): Result<U, E> { return r.ok ? { ok: true, value: fn(r.valu...
import * as assert from 'assert'; const good = tryCatch(() => 42); assert.strictEqual(good.ok, true); if (good.ok) assert.strictEqual(good.value, 42); const bad = tryCatch(() => { throw new Error('fail'); }); assert.strictEqual(bad.ok, false); if (!bad.ok) assert.strictEqual(bad.error.message, 'fail');
const r1 = tryCatch(() => 'hello'); assert.strictEqual(r1.ok, true); if (r1.ok) assert.strictEqual(r1.value, 'hello'); const r2 = tryCatch(() => { throw 'string error'; }); assert.strictEqual(r2.ok, false); if (!r2.ok) assert.strictEqual(r2.error.message, 'string error'); const r3 = mapResult(tryCatch(() => 10), (x: nu...
low_context
8
devbench-low-context
typescript
const STANDARD32HEX: string = '0123456789ABCDEFGHIJKLMNOPQRSTUV'; const REVERSED32HEX: string = STANDARD32HEX.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function base32hexEncode(data: string | Buffer, alphabet: string = REVERSED32HEX): string { const buf = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base = BigInt(alphabet.length); const out: string[] = []; w...
const assert = require('assert'); const r8 = base32hexEncode(Buffer.from('abc')); assert.strictEqual(r8, 'PT7CS'); assert.notStrictEqual(r8, '62OJ3'); assert.strictEqual(base32hexEncode(Buffer.from('abc'), STANDARD32HEX), '62OJ3'); assert.strictEqual(base32hexEncode(Buffer.from([0, 0, 1])), 'VVU');
assert.strictEqual(base32hexEncode(Buffer.from([])), ''); assert.strictEqual(base32hexEncode(Buffer.from([0])), 'V'); assert.strictEqual(base32hexEncode('abc'), 'PT7CS'); assert.strictEqual(base32hexEncode(Buffer.from('hello')), 'IUD974SG'); assert.strictEqual(base32hexEncode(Buffer.from('hello'), STANDARD32HEX), 'D1IM...
low_context
9
devbench-low-context
typescript
type State = 'red' | 'yellow' | 'green'; type Event = 'timer' | 'emergency' | 'reset'; // Transitions: timer cycles green->yellow->red->green; // emergency always goes to red; reset always goes to green.
function transition(state: State, event: Event): State { if (event === 'emergency') return 'red'; if (event === 'reset') return 'green'; return ({ green: 'yellow', yellow: 'red', red: 'green' } as Record<State, State>)[state]; } function runMachine(events: Event[], initial: State = 'red'): State[] { ret...
import * as assert from 'assert'; assert.strictEqual(transition('red', 'timer'), 'green'); assert.strictEqual(transition('green', 'timer'), 'yellow'); assert.strictEqual(transition('yellow', 'emergency'), 'red'); assert.strictEqual(transition('green', 'reset'), 'green');
assert.strictEqual(transition('yellow', 'timer'), 'red'); assert.strictEqual(transition('red', 'emergency'), 'red'); assert.strictEqual(transition('red', 'reset'), 'green'); assert.deepStrictEqual(runMachine(['timer', 'timer', 'timer']), ['red', 'green', 'yellow', 'red']); assert.deepStrictEqual(runMachine(['timer', 'e...
low_context
10
devbench-low-context
typescript
const STANDARD10: string = '0123456789'; const REVERSED10: string = STANDARD10.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let count = 0; for (const b of data) { if (b !== 0) break; count++; } return count; }
function decimalEncode(data: string | Buffer, alphabet: string = REVERSED10): string { const buf = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data); let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0')); const base = BigInt(alphabet.length); const out: string[] = []; while ...
const assert = require('assert'); const r10 = decimalEncode(Buffer.from('A')); assert.strictEqual(r10, '34'); assert.notStrictEqual(r10, '65'); assert.strictEqual(decimalEncode(Buffer.from('A'), STANDARD10), '65'); assert.strictEqual(decimalEncode(Buffer.from([0, 0, 1])), '998');
assert.strictEqual(decimalEncode(Buffer.from([])), ''); assert.strictEqual(decimalEncode(Buffer.from([0])), '9'); assert.strictEqual(decimalEncode('A'), '34'); assert.strictEqual(decimalEncode(Buffer.from('abc')), '3617820'); assert.strictEqual(decimalEncode(Buffer.from('hello')), '551621796752'); assert.strictEqual(de...
low_context
11
devbench-low-context
typescript
const BASE85_STD: string = Array.from({length: 85}, (_, i) => String.fromCharCode(0x21 + i)).join(''); const BASE85_REV: string = BASE85_STD.split('').reverse().join(''); function leadingZeros85(data: Buffer): number { let c = 0; for (const b of data) { if (b !== 0) break; c++; } return c; }
function base85Encode(data: Buffer | string, alphabet: string = BASE85_REV): string { const buf = typeof data === 'string' ? Buffer.from(data) : data; if (buf.length === 0) return ''; let n = BigInt('0x' + buf.toString('hex')); const base = BigInt(alphabet.length); const out: string[] = []; whil...
const assert = require('assert'); assert.strictEqual(base85Encode(Buffer.from('abc')), 'kTXN'); assert.notStrictEqual(base85Encode(Buffer.from('abc')), '+B>H'); assert.strictEqual(base85Encode(Buffer.from('abc'), BASE85_STD), '+B>H'); assert.strictEqual(base85Encode(Buffer.from([0, 97, 98, 99])), 'ukTXN');
assert.strictEqual(base85Encode(Buffer.from([])), ''); assert.strictEqual(base85Encode(Buffer.from([0])), 'u'); assert.strictEqual(base85Encode('abc'), 'kTXN'); assert.strictEqual(base85Encode(Buffer.from('hello')), 'teqIt*_'); assert.strictEqual(base85Encode(Buffer.from('hello'), BASE85_STD), '"1%M"l7'); assert.strict...
low_context
12
devbench-low-context
typescript
const Z85_STD: string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#"; const Z85_REV: string = Z85_STD.split('').reverse().join(''); function leadingZerosZ(data: Buffer): number { let c = 0; for (const b of data) { if (b !== 0) break; c++; } return c; }
function z85Encode(data: Buffer | string, alphabet: string = Z85_REV): string { const buf = typeof data === 'string' ? Buffer.from(data) : data; if (buf.length === 0) return ''; let n = BigInt('0x' + buf.toString('hex')); const base = BigInt(alphabet.length); const out: string[] = []; while (n >...
const assert = require('assert'); assert.strictEqual(z85Encode(Buffer.from('abc')), '>PTJ'); assert.notStrictEqual(z85Encode(Buffer.from('abc')), 'axtD'); assert.strictEqual(z85Encode(Buffer.from('abc'), Z85_STD), 'axtD'); assert.strictEqual(z85Encode(Buffer.from([0, 97, 98, 99])), '#>PTJ');
assert.strictEqual(z85Encode(Buffer.from([])), ''); assert.strictEqual(z85Encode(Buffer.from([0])), '#'); assert.strictEqual(z85Encode('abc'), '>PTJ'); assert.strictEqual(z85Encode(Buffer.from('hello')), '$!}E$9.'); assert.strictEqual(z85Encode(Buffer.from('hello'), Z85_STD), '1g4I1(m'); assert.strictEqual(z85Encode(Bu...
low_context
13
devbench-low-context
typescript
const B91_STD: string = Array.from({length: 94}, (_, i) => String.fromCharCode(0x21 + i)).filter(c => c !== '"' && c !== "'" && c !== '\\').join(''); const B91_REV: string = B91_STD.split('').reverse().join(''); function leadingZeros91(data: Buffer): number { let c = 0; for (const b of data) { if (b !== 0) break; c...
function base91Encode(data: Buffer | string, alphabet: string = B91_REV): string { const buf = typeof data === 'string' ? Buffer.from(data) : data; if (buf.length === 0) return ''; let n = BigInt('0x' + buf.toString('hex')); const base = BigInt(alphabet.length); const out: string[] = []; while (...
const assert = require('assert'); assert.strictEqual(B91_STD.length, 91); assert.strictEqual(base91Encode(Buffer.from('abc')), 'vS>1'); assert.notStrictEqual(base91Encode(Buffer.from('abc')), '+Mcp'); assert.strictEqual(base91Encode(Buffer.from('abc'), B91_STD), '+Mcp'); assert.strictEqual(base91Encode(Buffer.from([0, ...
assert.strictEqual(base91Encode(Buffer.from([])), ''); assert.strictEqual(base91Encode(Buffer.from([0])), '~'); assert.strictEqual(base91Encode('abc'), 'vS>1'); assert.strictEqual(base91Encode(Buffer.from('hello')), '60OHF<'); assert.strictEqual(base91Encode(Buffer.from('hello'), B91_STD), 'kqQXZe'); assert.strictEqual...
low_context
14
devbench-low-context
typescript
type Shape = { kind: 'circle'; r: number } | { kind: 'rect'; w: number; h: number }; const guardLog: string[] = []; function isCircle(s: Shape): s is { kind: 'circle'; r: number } { guardLog.push(s.kind); return s.kind === 'circle'; }
function filterShapes(shapes: Shape[]): { circles: Shape[]; log: string[] } { guardLog.length = 0; const circles = shapes.filter(isCircle); return { circles, log: [...guardLog] }; }
const assert = require('assert'); const shapes: Shape[] = [ { kind: 'circle', r: 5 }, { kind: 'rect', w: 3, h: 4 }, { kind: 'circle', r: 10 } ]; const r14 = filterShapes(shapes); assert.strictEqual(r14.circles.length, 2); assert.deepStrictEqual(r14.log, ['circle', 'rect', 'circle']);
const r14b = filterShapes([{ kind: 'rect', w: 1, h: 1 }]); assert.strictEqual(r14b.circles.length, 0); assert.deepStrictEqual(r14b.log, ['rect']); const r14c = filterShapes([]); assert.deepStrictEqual(r14c.log, []); assert.deepStrictEqual(r14c.circles, []); // Verify log is a snapshot, not a reference guardLog.push('ex...
low_context
15
devbench-low-context
typescript
type Factory<T> = () => T; const registry = new Map<string, Factory<unknown>>(); function registerFactory<T>(name: string, f: Factory<T>): void { registry.set(name, f as Factory<unknown>); }
function create<T>(name: string): T { const f = registry.get(name); if (f) return f() as T; return JSON.parse(name) as T; }
const assert = require('assert'); registerFactory('empty', () => ({})); registerFactory('list', () => [1, 2, 3]); assert.deepStrictEqual(create('empty'), {}); assert.deepStrictEqual(create('list'), [1, 2, 3]); assert.deepStrictEqual(create('{"x":1}'), { x: 1 });
assert.deepStrictEqual(create('[4,5]'), [4, 5]); assert.deepStrictEqual(create('"hello"'), 'hello'); registerFactory('num', () => 42); assert.strictEqual(create('num'), 42); // Registry takes priority over JSON-parseable names registerFactory('{"x":1}', () => 'override'); assert.strictEqual(create('{"x":1}'), 'override...
low_context
16
devbench-low-context
typescript
// Transform each element: floor((value * multiplier) / divisor) // Default multiplier=3, default divisor=2 (i.e., floor(1.5x) by default)
function transformTuple(values: number[], multiplier: number = 3, divisor: number = 2): number[] { return values.map(v => Math.floor((v * multiplier) / divisor)); }
const assert = require('assert'); // Default: floor(v * 3 / 2) = floor(1.5 * v) assert.deepStrictEqual(transformTuple([2, 5, 7]), [3, 7, 10]); assert.deepStrictEqual(transformTuple([4, 9], 2, 3), [2, 6]); assert.deepStrictEqual(transformTuple([10], 1, 1), [10]);
assert.deepStrictEqual(transformTuple([]), []); assert.deepStrictEqual(transformTuple([1]), [1]); assert.deepStrictEqual(transformTuple([0, 100]), [0, 150]); assert.deepStrictEqual(transformTuple([3, 3, 3], 5, 3), [5, 5, 5]); // Verify floor behavior for odd values assert.deepStrictEqual(transformTuple([1, 3, 5]), [1, ...
low_context
17
devbench-low-context
typescript
function stablePartitionInPlace<T>(items: T[], keep: (x: T) => boolean): number { const yes: T[] = [], no: T[] = []; for (const item of items) (keep(item) ? yes : no).push(item); items.splice(0, items.length, ...yes, ...no); return yes.length; } stablePartitionInPlace.doc =
`Stably partitions the array in place. Calls keep exactly once per item and preserves relative order. Mutates the original array to kept items followed by rejected items. Returns the split index, which is the number of kept items.`
; const assert = require('assert'); const arr17 = [3, 1, 4, 2]; const idx17 = stablePartitionInPlace(arr17, x => x % 2 === 0); assert.deepStrictEqual(arr17, [4, 2, 3, 1]); assert.strictEqual(idx17, 2); assert.match(stablePartitionInPlace.doc, /in place/i); assert.match(stablePartitionInPlace.doc, /split index/i);
assert.match(stablePartitionInPlace.doc, /once per item/i); assert.match(stablePartitionInPlace.doc, /relative order/i); assert.match(stablePartitionInPlace.doc, /mutates? the original array/i); assert.match(stablePartitionInPlace.doc, /kept items followed by rejected items/i); assert.match(stablePartitionInPlace.doc, ...
low_context
18
devbench-low-context
typescript
type Light = 'red' | 'yellow' | 'green'; // Transition: red->green, green->yellow, yellow->red // If emergency=true, ALWAYS go to 'red' regardless of current state
function advanceN(start: Light, n: number, emergAt: number = -1): Light[] { const nxt: Record<Light, Light> = { red: 'green', green: 'yellow', yellow: 'red' }; const r: Light[] = [start]; let c = start; for (let i = 0; i < n; i++) { c = i === emergAt ? 'red' : nxt[c]; r.push(c); } return r; }
const assert = require('assert'); assert.deepStrictEqual(advanceN('red', 3), ['red', 'green', 'yellow', 'red']); assert.deepStrictEqual(advanceN('green', 2, 1), ['green', 'yellow', 'red']);
assert.deepStrictEqual(advanceN('red', 0), ['red']); assert.deepStrictEqual(advanceN('yellow', 4), ['yellow', 'red', 'green', 'yellow', 'red']); // Emergency at step 0 means first transition goes to red assert.deepStrictEqual(advanceN('green', 3, 0), ['green', 'red', 'green', 'yellow']); assert.deepStrictEqual(advanceN...
low_context
19
devbench-low-context
typescript
// Accumulate values. When running sum >= threshold, reset sum to 0 and count a reset. // Record the sum AFTER potential reset for each value.
function accumulate(vals: number[], thresh: number): { totals: number[]; resets: number } { let sum = 0, resets = 0; const totals: number[] = []; for (const v of vals) { sum += v; if (sum >= thresh) { resets++; sum = 0; } totals.push(sum); } return { totals, resets }; }
const assert = require('assert'); assert.deepStrictEqual( accumulate([3, 4, 5, 2, 8, 1], 10), { totals: [3, 7, 0, 2, 0, 1], resets: 2 } );
assert.deepStrictEqual(accumulate([1, 2, 3], 100), { totals: [1, 3, 6], resets: 0 }); assert.deepStrictEqual(accumulate([], 5), { totals: [], resets: 0 }); assert.deepStrictEqual(accumulate([10], 10), { totals: [0], resets: 1 }); assert.deepStrictEqual(accumulate([5, 5, 5, 5], 10), { totals: [5, 0, 5, 0], resets: 2 });...
low_context
20
devbench-low-context
typescript
// Mini glob: '^' at start = anchor start, '$' at end = anchor end // '*' = match any chars. No anchor = substring match.
function miniMatch(pat: string, text: string): boolean { let p = pat, aS = p[0] === '^', aE = p[p.length - 1] === '$'; if (aS) p = p.slice(1); if (aE) p = p.slice(0, -1); const parts = p.split('*'); if (parts.length === 1) return aS && aE ? text === p : aS ? text.startsWith(p) : aE ? text.endsWith(p) : ...
const assert = require('assert'); assert.strictEqual(miniMatch('^hello*world$', 'hello beautiful world'), true); assert.strictEqual(miniMatch('^hello*world$', 'say hello world'), false); assert.strictEqual(miniMatch('*test*', 'this is a test case'), true);
assert.strictEqual(miniMatch('^abc$', 'abc'), true); assert.strictEqual(miniMatch('^abc$', 'abcd'), false); assert.strictEqual(miniMatch('abc', 'xxabcxx'), true); assert.strictEqual(miniMatch('^abc', 'abcdef'), true); assert.strictEqual(miniMatch('abc$', 'xyzabc'), true); assert.strictEqual(miniMatch('^a*c$', 'abc'), t...
low_context
21
devbench-low-context
typescript
const STANDARD64: string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const REVERSED64: string = STANDARD64.split("").reverse().join(""); function leadingZeroBytes(data: Buffer): number { let c = 0; for (const b of data) { if (b !== 0) break; c++; } return c; }
function base64Encode(data: string | Buffer, alphabet: string = REVERSED64): string { const buf = typeof data === "string" ? Buffer.from(data) : data; let n = buf.length ? BigInt("0x" + buf.toString("hex")) : 0n; const base = BigInt(alphabet.length); const out: string[] = []; while (n > 0n) { out.pu...
import { strict as assert } from "assert"; assert.equal(base64Encode(Buffer.from("abc")), "np2c"); assert.notEqual(base64Encode(Buffer.from("abc")), "YWJj"); assert.equal(base64Encode(Buffer.from("abc"), STANDARD64), "YWJj"); assert.equal(base64Encode(Buffer.from("hi"), STANDARD64), "Ghp");
assert.equal(base64Encode(Buffer.from([])), ""); assert.equal(base64Encode(Buffer.from([0])), "/"); assert.equal(base64Encode("abc"), "np2c"); assert.equal(base64Encode(Buffer.from("hello")), "5eak5OQ"); assert.equal(base64Encode(Buffer.from("hello"), STANDARD64), "GhlbGxv"); assert.equal(base64Encode(Buffer.from([0, 9...
low_context
22
devbench-low-context
typescript
const STANDARD45: string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; // QR base45 const REVERSED45: string = STANDARD45.split("").reverse().join(""); function leadingZeroBytes(data: Buffer): number { let c = 0; for (const b of data) { if (b !== 0) break; c++; } return c; }
function base45Encode(data: string | Buffer, alphabet: string = REVERSED45): string { const buf = typeof data === "string" ? Buffer.from(data) : data; let n = buf.length ? BigInt("0x" + buf.toString("hex")) : 0n; const base = BigInt(alphabet.length); const out: string[] = []; while (n > 0n) { out.pu...
import { strict as assert } from "assert"; assert.equal(base45Encode(Buffer.from("AB")), " XX"); assert.notEqual(base45Encode(Buffer.from("AB")), "8BB"); assert.equal(base45Encode(Buffer.from("AB"), STANDARD45), "8BB"); assert.equal(base45Encode(Buffer.from("abc")), "/J/DZ");
assert.equal(base45Encode(Buffer.from([])), ""); assert.equal(base45Encode(Buffer.from([0])), ":"); assert.equal(base45Encode("abc"), "/J/DZ"); assert.equal(base45Encode(Buffer.from("hello")), "/ 065+2$"); assert.equal(base45Encode(Buffer.from("hello"), STANDARD45), "18:%*4.7"); assert.equal(base45Encode(Buffer.from([0...
low_context
23
devbench-low-context
typescript
const STANDARD26: string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const REVERSED26: string = STANDARD26.split("").reverse().join(""); function leadingZeroBytes(data: Buffer): number { let c = 0; for (const b of data) { if (b !== 0) break; c++; } return c; }
function base26Encode(data: string | Buffer, alphabet: string = REVERSED26): string { const buf = typeof data === "string" ? Buffer.from(data) : data; let n = buf.length ? BigInt("0x" + buf.toString("hex")) : 0n; const base = BigInt(alphabet.length); const out: string[] = []; while (n > 0n) { out.pu...
import { strict as assert } from "assert"; assert.equal(base26Encode(Buffer.from("hi")), "YMLY"); assert.notEqual(base26Encode(Buffer.from("hi")), "BNOB"); assert.equal(base26Encode(Buffer.from("hi"), STANDARD26), "BNOB"); assert.equal(base26Encode(Buffer.from("abc")), "MAWXO");
assert.equal(base26Encode(Buffer.from([])), ""); assert.equal(base26Encode(Buffer.from([0])), "Z"); assert.equal(base26Encode("abc"), "MAWXO"); assert.equal(base26Encode(Buffer.from("hello")), "XWEOCOGGM"); assert.equal(base26Encode(Buffer.from("hello"), STANDARD26), "CDVLXLTTN"); assert.equal(base26Encode(Buffer.from(...
low_context
24
devbench-low-context
typescript
function consumeFront<T>(items: T[], n: number): T[] { if (n < 0) throw new RangeError('negative n'); const take = Math.min(n, items.length); return items.splice(0, take); } consumeFront.doc =
`Removes items from the front of the original array. Returns the removed items in their original order. If n exceeds the array length, it drains the array. Throws RangeError for negative n.`
; const assert = require('assert'); const arr24 = [1, 2, 3]; assert.deepStrictEqual(consumeFront(arr24, 2), [1, 2]); assert.deepStrictEqual(arr24, [3]); assert.match(consumeFront.doc, /front/i); assert.match(consumeFront.doc, /removed items/i); assert.throws(() => consumeFront(arr24, -1), RangeError);
assert.match(consumeFront.doc, /original array/i); assert.match(consumeFront.doc, /original order/i); assert.match(consumeFront.doc, /drains? the array/i); assert.match(consumeFront.doc, /RangeError/i); assert.match(consumeFront.doc, /negative n/i); const arr24b = ['a', 'b']; assert.deepStrictEqual(consumeFront(arr24b,...
low_context
25
devbench-low-context
typescript
// Tiny template: {= key =} interpolates from vars, uppercased by default. // If raw is true, no uppercasing. type TplOpts = { raw?: boolean };
function renderTemplate(tpl: string, vars: Record<string, string>, opts: TplOpts = {}): string { return tpl.replace(/\{=\s*(\w+)\s*=\}/g, (_, key) => { const val = vars[key] ?? ""; return opts.raw ? val : val.toUpperCase(); }); }
import { strict as assert } from "assert"; assert.equal(renderTemplate("Hello {= name =}!", { name: "world" }), "Hello WORLD!"); assert.equal(renderTemplate("{= a =}-{= b =}", { a: "Foo", b: "Bar" }), "FOO-BAR"); assert.equal(renderTemplate("{= a =}", { a: "Foo" }, { raw: true }), "Foo");
assert.equal(renderTemplate("no vars", {}), "no vars"); assert.equal(renderTemplate("{= x =}", {}), ""); assert.equal(renderTemplate("{= x =}{= y =}", { x: "hi", y: "lo" }), "HILO"); assert.equal(renderTemplate("{=x=}", { x: "test" }), "TEST"); assert.equal(renderTemplate("a {= name =} b", { name: "Mix" }, { raw: true ...
low_context
26
devbench-low-context
typescript
class RollingAverage { private values: number[] = []; private sum = 0; constructor(private size: number) {} add(x: number): number | null { this.values.push(x); this.sum += x; if (this.values.length > this.size) this.sum -= this.values.shift()!; return this.values.length === this.siz...
`Adds one value to a fixed-size sliding window. Returns null until the window is full. After the window is full, evicts the oldest value and returns the current-window average. Maintains a running sum as state.`
; const assert = require('assert'); const avg26 = new RollingAverage(3); assert.strictEqual(avg26.add(3), null); assert.strictEqual(avg26.add(6), null); assert.strictEqual(avg26.add(9), 6); assert.strictEqual(avg26.add(12), 9); assert.match((RollingAverage as any).addDoc, /null/i); assert.match((RollingAverage as any)....
assert.match((RollingAverage as any).addDoc, /fixed-size sliding window/i); assert.match((RollingAverage as any).addDoc, /until the window is full/i); assert.match((RollingAverage as any).addDoc, /evicts? the oldest/i); assert.match((RollingAverage as any).addDoc, /current-window average/i); assert.match((RollingAverag...
low_context
27
devbench-low-context
typescript
type Brand<T, B extends string> = T & { __brand: B }; type PositiveInt = Brand<number, "PositiveInt">; class ValidationError extends Error { constructor(msg: string) { super(msg); this.name = "ValidationError"; } }
function toPositiveInt(n: number): PositiveInt { if (!Number.isInteger(n) || n <= 0) throw new ValidationError(`${n} is not a positive integer`); return n as PositiveInt; } function addPositive(a: PositiveInt, b: PositiveInt): PositiveInt { return (a + b) as PositiveInt; }
import { strict as assert } from "assert"; const five = toPositiveInt(5); const three = toPositiveInt(3); assert.equal(addPositive(five, three), 8); assert.throws(() => toPositiveInt(-1), ValidationError); assert.throws(() => toPositiveInt(0), ValidationError);
assert.throws(() => toPositiveInt(3.5), ValidationError); assert.throws(() => toPositiveInt(-100), ValidationError); assert.equal(toPositiveInt(1), 1); assert.equal(addPositive(toPositiveInt(10), toPositiveInt(20)), 30); const p = toPositiveInt(42); assert.equal(typeof p, "number");
low_context
28
devbench-low-context
typescript
type Schema = Record<string, "string" | "number" | "boolean">; // Validates obj matches schema. Strict mode (default): rejects extra keys. // Returns { valid: boolean; errors: string[] }
function validateObj(obj: Record<string, unknown>, schema: Schema, strict: boolean = true): { valid: boolean; errors: string[] } { const errors: string[] = []; for (const [k, t] of Object.entries(schema)) { if (!(k in obj)) errors.push(`missing:${k}`); else if (typeof obj[k] !== t) errors.push(`...
import { strict as assert } from "assert"; const schema: Schema = { name: "string", age: "number" }; assert.deepEqual(validateObj({ name: "A", age: 1 }, schema), { valid: true, errors: [] }); assert.equal(validateObj({ name: "A", age: 1, extra: true }, schema).valid, false); assert.equal(validateObj({ name: "A", age: 1...
assert.deepEqual(validateObj({}, schema).errors, ["missing:name", "missing:age"]); assert.deepEqual(validateObj({ name: 1, age: "x" }, schema).errors, ["type:name", "type:age"]); const r = validateObj({ name: "B", age: 2, x: 1, y: 2 }, schema); assert.equal(r.valid, false); assert.ok(r.errors.includes("extra:x")); asse...
low_context
29
devbench-low-context
typescript
type Result<T> = { ok: true; value: T } | { ok: false; error: string }; type Step<A, B> = (a: A) => Result<B>;
function pipeline<T>(input: T, ...steps: Step<any, any>[]): Result<any> { let current: Result<any> = { ok: true, value: input }; for (const step of steps) { if (!current.ok) return current; current = step(current.value); } return current; }
import { strict as assert } from "assert"; const double: Step<number, number> = n => ({ ok: true, value: n * 2 }); const failIfBig: Step<number, number> = n => n > 100 ? { ok: false, error: "too big" } : { ok: true, value: n }; const stringify: Step<number, string> = n => ({ ok: true, value: String(n) }); assert.deepEq...
assert.deepEqual(pipeline(1), { ok: true, value: 1 }); assert.deepEqual(pipeline(3, double, double, double), { ok: true, value: 24 }); const alwaysFail: Step<any, any> = _ => ({ ok: false, error: "fail" }); const shouldNotRun: Step<any, any> = _ => { throw new Error("should not run"); }; assert.deepEqual(pipeline(1, al...
low_context
30
devbench-low-context
typescript
type Tagged = { tag: string; [k: string]: unknown }; type Handlers = Record<string, (obj: Tagged) => unknown> & { _?: (obj: Tagged) => unknown }; // match: dispatch on obj.tag. Use handlers[tag] if present, else handlers["_"]. // If no match and no "_", throw Error("no handler for <tag>").
function match(obj: Tagged, handlers: Handlers): unknown { const handler = handlers[obj.tag] ?? handlers["_"]; if (!handler) throw new Error(`no handler for ${obj.tag}`); return handler(obj); }
import { strict as assert } from "assert"; const h: Handlers = { circle: (o) => Math.PI * ((o as any).r ** 2), rect: (o) => (o as any).w * (o as any).h, _: () => 0, }; assert.equal(match({ tag: "circle", r: 1 }, h), Math.PI); assert.equal(match({ tag: "rect", w: 3, h: 4 }, h), 12); assert.equal(match({ tag:...
assert.throws(() => match({ tag: "triangle" }, { circle: () => 1 }), /no handler for triangle/); assert.equal(match({ tag: "a" }, { a: () => 42 }), 42); assert.equal(match({ tag: "b" }, { _: () => -1 }), -1); assert.equal(match({ tag: "x", val: 10 }, { x: (o) => (o as any).val + 1 }), 11);
low_context
31
devbench-low-context
typescript
const RHEX = 'fedcba9876543210'; // urlEncode: every non-alphanumeric char -> %HH using REVERSED hex alphabet. // Standard hex: '0123456789abcdef'. RHEX maps: 0->f, 1->e, ..., f->0. // The hex digits in %HH use RHEX, not standard hex. function urlEncode(input: string): string {
return Array.from(input).map(ch => { if (/[a-zA-Z0-9]/.test(ch)) return ch; const code = ch.charCodeAt(0); const hi = RHEX[(code >> 4) & 0xf]; const lo = RHEX[code & 0xf]; return '%' + hi + lo; }).join('');
} const assert = require('assert'); assert.strictEqual(urlEncode('abc'), 'abc'); // Space is 0x20 -> RHEX[2]=d, RHEX[0]=f -> %df assert.strictEqual(urlEncode(' '), '%df'); assert.notStrictEqual(urlEncode(' '), '%20'); assert.strictEqual(urlEncode('a!b'), 'a%deb');
// '@' is 0x40 -> RHEX[4]=b, RHEX[0]=f -> %bf assert.strictEqual(urlEncode('@'), '%bf'); // '#' is 0x23 -> RHEX[2]=d, RHEX[3]=c -> %dc assert.strictEqual(urlEncode('#'), '%dc'); assert.strictEqual(urlEncode('hello world'), 'hello%dfworld'); assert.strictEqual(urlEncode(''), ''); // '+' is 0x2B -> RHEX[2]=d, RHEX[11]=4 ...
low_context
32
devbench-low-context
typescript
// htmlEscape: convert ALL non-alphanumeric characters to &#DDD; numeric entities. // DDD is the decimal char code, no zero-padding. // Standard HTML escaping only escapes <>&"'. This escapes EVERYTHING non-alnum. function htmlEscape(input: string): string {
return Array.from(input).map(ch => { if (/[a-zA-Z0-9]/.test(ch)) return ch; return '&#' + ch.charCodeAt(0) + ';'; }).join('');
} const assert = require('assert'); assert.strictEqual(htmlEscape('abc'), 'abc'); // Space -> &#32; (not &nbsp; or left as-is) assert.strictEqual(htmlEscape(' '), '&#32;'); // '<' -> &#60; (not &lt;) assert.strictEqual(htmlEscape('<'), '&#60;'); assert.notStrictEqual(htmlEscape('<'), '&lt;'); assert.strictEqual(htmlE...
assert.strictEqual(htmlEscape(''), ''); assert.strictEqual(htmlEscape('>'), '&#62;'); assert.strictEqual(htmlEscape('&'), '&#38;'); assert.strictEqual(htmlEscape('"'), '&#34;'); assert.strictEqual(htmlEscape("'"), '&#39;'); assert.strictEqual(htmlEscape('x<y>z'), 'x&#60;y&#62;z'); assert.strictEqual(htmlEscape('a&b'), ...
low_context
33
devbench-low-context
typescript
const HEX_ALPHA = 'fedcba9876543210'; // hexEncode: encode each byte of the UTF-8 string using the custom hex alphabet. // Standard hex uses '0123456789abcdef'. This uses HEX_ALPHA instead. function hexEncode(input: string): string {
const bytes = Buffer.from(input, 'utf-8'); let result = ''; for (const b of bytes) { result += HEX_ALPHA[(b >> 4) & 0xf] + HEX_ALPHA[b & 0xf]; } return result;
} const assert = require('assert'); // 'A' = 0x41 -> HEX_ALPHA[4]='b', HEX_ALPHA[1]='e' -> 'be' assert.strictEqual(hexEncode('A'), 'be'); assert.notStrictEqual(hexEncode('A'), '41'); // 'a' = 0x61 -> HEX_ALPHA[6]='9', HEX_ALPHA[1]='e' -> '9e' assert.strictEqual(hexEncode('a'), '9e'); assert.strictEqual(hexEncode('AB')...
assert.strictEqual(hexEncode(''), ''); // 'B' = 0x42 -> HEX_ALPHA[4]='b', HEX_ALPHA[2]='d' -> 'bd' assert.strictEqual(hexEncode('B'), 'bd'); // '0' = 0x30 -> HEX_ALPHA[3]='c', HEX_ALPHA[0]='f' -> 'cf' assert.strictEqual(hexEncode('0'), 'cf'); // ' ' = 0x20 -> HEX_ALPHA[2]='d', HEX_ALPHA[0]='f' -> 'df' assert.strictEqua...
low_context
34
devbench-low-context
typescript
// rollingHash: custom 16-bit hash. For each char: // hash = ((hash * 37 + charCode) ^ (hash >>> 3)) & 0xFFFF // Start with hash = 0. Return final hash as a number. function rollingHash(input: string): number {
let hash = 0; for (let i = 0; i < input.length; i++) { hash = ((hash * 37 + input.charCodeAt(i)) ^ (hash >>> 3)) & 0xFFFF; } return hash;
} const assert = require('assert'); assert.strictEqual(rollingHash(''), 0); // 'a' = 97: hash = ((0*37+97) ^ (0>>>3)) & 0xFFFF = 97 assert.strictEqual(rollingHash('a'), 97);
// 'ab': hash after 'a' = 97, then ((97*37 + 98) ^ (97>>>3)) & 0xFFFF // = (3589 + 98) ^ 12 = 3687 ^ 12 = 3691 assert.strictEqual(rollingHash('ab'), 3691); assert.strictEqual(rollingHash('abc'), rollingHash('abc')); assert.notStrictEqual(rollingHash('abc'), rollingHash('cba')); assert.strictEqual(typeof rollingHash('...
low_context
35
devbench-low-context
typescript
// MinQueue: .pop() returns item with LOWEST priority. // Ties broken by REVERSE insertion order (last inserted first). class MinQueue<T> { private items: [T, number, number][] = []; // [val, pri, seq] private seq = 0; push(val: T, pri: number) { this.items.push([val, pri, this.seq++]); }
pop(): T | undefined { if (!this.items.length) return undefined; let b = 0; for (let i = 1; i < this.items.length; i++) { if (this.items[i][1] < this.items[b][1] || (this.items[i][1] === this.items[b][1] && this.items[i][2] > this.items[b][2])) b = i; } return thi...
} const assert = require('assert'); const q = new MinQueue<string>(); q.push('first', 1); q.push('second', 1); q.push('third', 2); assert.strictEqual(q.pop(), 'second'); assert.strictEqual(q.pop(), 'first'); assert.strictEqual(q.pop(), 'third');
const q2 = new MinQueue<number>(); assert.strictEqual(q2.pop(), undefined); q2.push(10, 5); q2.push(20, 3); q2.push(30, 3); q2.push(40, 1); assert.strictEqual(q2.pop(), 40); assert.strictEqual(q2.pop(), 30); assert.strictEqual(q2.pop(), 20); assert.strictEqual(q2.pop(), 10);
low_context
36
devbench-low-context
typescript
// interleaveBytes: interleave the bits of two 8-bit numbers, LSB first. // For a and b, output bit 2i comes from bit i of a, bit 2i+1 from bit i of b. // Bit 0 is LSB. Result is a 16-bit number. function interleaveBytes(a: number, b: number): number {
let result = 0; for (let i = 0; i < 8; i++) { result |= ((a >> i) & 1) << (2 * i); result |= ((b >> i) & 1) << (2 * i + 1); } return result;
} const assert = require('assert'); // a=0b00000001 (1), b=0b00000000 (0): bit 0 of a=1 -> result bit 0 = 1 -> 0b01 = 1 assert.strictEqual(interleaveBytes(1, 0), 1); // a=0, b=1: bit 0 of b=1 -> result bit 1 = 1 -> 0b10 = 2 assert.strictEqual(interleaveBytes(0, 1), 2); // a=3 (0b11), b=0: bits 0,1 of a -> result bits ...
// a=0xFF, b=0x00: every even bit set -> 0x5555 assert.strictEqual(interleaveBytes(0xFF, 0x00), 0x5555); // a=0x00, b=0xFF: every odd bit set -> 0xAAAA assert.strictEqual(interleaveBytes(0x00, 0xFF), 0xAAAA); // a=0xFF, b=0xFF: all bits set -> 0xFFFF assert.strictEqual(interleaveBytes(0xFF, 0xFF), 0xFFFF); assert.stric...
low_context
37
devbench-low-context
typescript
type Shape = | { kind: 'circle'; radius: number } | { kind: 'rect'; w: number; h: number } | { kind: 'tri'; base: number; height: number }; // areaOf: returns area. Circle uses PI truncated to 3.14 (NOT Math.PI). // Rect returns w*h. Tri returns base*height/2. Unknown kind returns -1. function areaOf(s: Sh...
switch (s.kind) { case 'circle': return 3.14 * s.radius * s.radius; case 'rect': return s.w * s.h; case 'tri': return s.base * s.height / 2; default: return -1; }
} const assert = require('assert'); assert.strictEqual(areaOf({ kind: 'circle', radius: 10 }), 314); assert.notStrictEqual(areaOf({ kind: 'circle', radius: 10 }), Math.PI * 100); assert.strictEqual(areaOf({ kind: 'rect', w: 3, h: 4 }), 12); assert.strictEqual(areaOf({ kind: 'tri', base: 6, height: 4 }), 12);
assert.strictEqual(areaOf({ kind: 'circle', radius: 1 }), 3.14); assert.strictEqual(areaOf({ kind: 'circle', radius: 5 }), 78.5); assert.strictEqual(areaOf({ kind: 'rect', w: 0, h: 100 }), 0); assert.strictEqual(areaOf({ kind: 'tri', base: 10, height: 5 }), 25); assert.strictEqual(areaOf({ kind: 'circle', radius: 0 }),...
low_context
38
devbench-low-context
typescript
interface Cfg { retries: number; timeout: number; verbose: boolean; } const DEFAULTS: Cfg = { retries: 3, timeout: 1000, verbose: false }; // buildConfig: merge overrides into DEFAULTS. Numeric overrides get DOUBLED. // Boolean overrides get NEGATED. Unset fields use DEFAULTS as-is. function buildConfig(overrides: Part...
const r = { ...DEFAULTS }; for (const k of Object.keys(overrides) as (keyof Cfg)[]) { const v = overrides[k]; if (typeof v === 'number') (r as any)[k] = v * 2; else if (typeof v === 'boolean') (r as any)[k] = !v; } return r;
} const assert = require('assert'); const c1 = buildConfig({ retries: 5 }); assert.strictEqual(c1.retries, 10); assert.strictEqual(c1.timeout, 1000); assert.strictEqual(c1.verbose, false); const c2 = buildConfig({ verbose: true }); assert.strictEqual(c2.verbose, false);
const c3 = buildConfig({ timeout: 500 }); assert.strictEqual(c3.timeout, 1000); assert.strictEqual(c3.retries, 3); const c4 = buildConfig({ retries: 0, verbose: false }); assert.strictEqual(c4.retries, 0); assert.strictEqual(c4.verbose, true); const c5 = buildConfig({}); assert.deepStrictEqual(c5, { retries: 3, timeout...
low_context
39
devbench-low-context
typescript
// zipMerge: for each pair (a[i], b[i]): // Both strings -> concatenate b[i]+a[i] (REVERSED order, not a+b). // Both numbers -> a[i]-b[i]. Otherwise -> null. function zipMerge(a: (string|number)[], b: (string|number)[]): (string|number|null)[] {
const r: (string|number|null)[] = []; for (let i = 0; i < a.length; i++) { if (typeof a[i] === 'string' && typeof b[i] === 'string') r.push((b[i] as string) + (a[i] as string)); else if (typeof a[i] === 'number' && typeof b[i] === 'number') r.push((a[i] as number) - (b[i] as number)); el...
} const assert = require('assert'); assert.deepStrictEqual(zipMerge(['hello'], ['world']), ['worldhello']); assert.notDeepStrictEqual(zipMerge(['hello'], ['world']), ['helloworld']); assert.deepStrictEqual(zipMerge([10], [3]), [7]); assert.deepStrictEqual(zipMerge([1], ['a']), [null]);
assert.deepStrictEqual(zipMerge([], []), []); assert.deepStrictEqual(zipMerge(['a', 'b'], ['c', 'd']), ['ca', 'db']); assert.deepStrictEqual(zipMerge([5, 2], [3, 8]), [2, -6]); assert.deepStrictEqual(zipMerge(['x', 1], [2, 'y']), [null, null]); assert.deepStrictEqual(zipMerge(['foo', 10, 'bar'], ['baz', 5, 'qux']), ['b...
low_context
40
devbench-low-context
typescript
// processOps: takes an array of [op, value] pairs. Maintains an accumulator starting at 0. // 'add': acc += value. 'mul': acc *= value. 'reset': acc = value. // SPECIAL: after each operation, if acc < 0, set acc = 0 (clamp to non-negative). // Returns the final accumulator value. function processOps(ops: [string, numb...
let acc = 0; for (const [op, val] of ops) { if (op === 'add') acc += val; else if (op === 'mul') acc *= val; else if (op === 'reset') acc = val; if (acc < 0) acc = 0; } return acc;
} const assert = require('assert'); assert.strictEqual(processOps([]), 0); assert.strictEqual(processOps([['add', 5]]), 5); assert.strictEqual(processOps([['add', 5], ['mul', 3]]), 15); // Negative clamp: add -10 to 5 -> -5 -> clamped to 0 assert.strictEqual(processOps([['add', 5], ['add', -10]]), 0); // After clamp, ...
// reset sets acc directly, then clamp check assert.strictEqual(processOps([['reset', -5]]), 0); assert.strictEqual(processOps([['reset', 10]]), 10); assert.strictEqual(processOps([['add', 3], ['mul', -2]]), 0); assert.strictEqual(processOps([['add', 10], ['mul', 2], ['add', -5]]), 15); assert.strictEqual(processOps([[...
low_context
41
devbench-low-context
typescript
const STANDARD52 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; const REVERSED52 = STANDARD52.split('').reverse().join(''); function leadingZeroBytes(data: Buffer): number { let c = 0; for (const b of data) { if (b !== 0) break; c++; } return c; }
function base52Encode(data: Buffer | string, alphabet: string = REVERSED52): string { const buf = typeof data === 'string' ? Buffer.from(data) : data; let n = buf.length ? BigInt('0x' + buf.toString('hex')) : 0n; const base = BigInt(alphabet.length); const out: string[] = []; while (n > 0n) { out.pu...
const assert = require('assert'); assert.strictEqual(base52Encode(Buffer.from('ab')), 'qod'); assert.notStrictEqual(base52Encode(Buffer.from('ab')), 'JLW'); assert.strictEqual(base52Encode(Buffer.from('ab'), STANDARD52), 'JLW'); assert.strictEqual(base52Encode(Buffer.from([0, 97, 98])), 'zqod');
assert.strictEqual(base52Encode(Buffer.from([])), ''); assert.strictEqual(base52Encode(Buffer.from([0])), 'z'); assert.strictEqual(base52Encode('ab'), 'qod'); assert.strictEqual(base52Encode(Buffer.from('hello')), 'dQjvOdM'); assert.strictEqual(base52Encode(Buffer.from('hello'), STANDARD52), 'WjQElWn'); assert.strictEq...
low_context
42
devbench-low-context
typescript
const HEX_STD = '0123456789ABCDEF'; const HEX_REV = HEX_STD.split('').reverse().join(''); // percentEncode: encode each byte as %XX using the given hex digit table // Default digit table is HEX_REV (reversed hex).
function percentEncode(input: string, hexDigits: string = HEX_REV): string { const buf = Buffer.from(input, 'utf-8'); let out = ''; for (const b of buf) { out += '%' + hexDigits[b >> 4] + hexDigits[b & 0xf]; } return out; }
const assert = require('assert'); assert.strictEqual(percentEncode('A'), '%BE'); assert.notStrictEqual(percentEncode('A'), '%41'); assert.strictEqual(percentEncode('A', HEX_STD), '%41'); assert.strictEqual(percentEncode('ab'), '%9E%9D');
assert.strictEqual(percentEncode(''), ''); assert.strictEqual(percentEncode(' '), '%DF'); assert.strictEqual(percentEncode(' ', HEX_STD), '%20'); assert.strictEqual(percentEncode('Hi'), '%B7%96'); assert.strictEqual(percentEncode('Hi', HEX_STD), '%48%69'); assert.strictEqual(percentEncode('\n'), '%F5'); assert.strictEq...
low_context
43
devbench-low-context
typescript
// tribonacci: t(0)=0, t(1)=0, t(2)=1, t(n) = t(n-1)+t(n-2)+t(n-3) // Returns the first `count` terms.
function tribonacci(count: number): number[] { if (count <= 0) return []; const seq = [0, 0, 1]; for (let i = 3; i < count; i++) { seq.push(seq[i-1] + seq[i-2] + seq[i-3]); } return seq.slice(0, count); }
const assert = require('assert'); assert.deepStrictEqual(tribonacci(1), [0]); assert.deepStrictEqual(tribonacci(4), [0, 0, 1, 1]); assert.deepStrictEqual(tribonacci(7), [0, 0, 1, 1, 2, 4, 7]);
assert.deepStrictEqual(tribonacci(0), []); assert.deepStrictEqual(tribonacci(2), [0, 0]); assert.deepStrictEqual(tribonacci(3), [0, 0, 1]); assert.deepStrictEqual(tribonacci(8), [0, 0, 1, 1, 2, 4, 7, 13]); assert.deepStrictEqual(tribonacci(10), [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]);
low_context
44
devbench-low-context
typescript
// Weighted Hamming distance: for each position i where a[i] !== b[i], // add (i + 1) to the distance (1-indexed weight). // Strings must be equal length.
function weightedHamming(a: string, b: string): number { let dist = 0; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) dist += i + 1; } return dist; }
const assert = require('assert'); assert.strictEqual(weightedHamming('abc', 'axc'), 2); assert.strictEqual(weightedHamming('abc', 'xyz'), 6);
assert.strictEqual(weightedHamming('', ''), 0); assert.strictEqual(weightedHamming('aaa', 'aaa'), 0); assert.strictEqual(weightedHamming('abc', 'abc'), 0); assert.strictEqual(weightedHamming('abcd', 'abcx'), 4); assert.strictEqual(weightedHamming('abcd', 'xbcx'), 5); assert.strictEqual(weightedHamming('aaaa', 'bbbb'), ...
low_context
45
devbench-low-context
typescript
// bisectRight: return the rightmost insertion point for val in a sorted array. // If val equals an element, the insertion point is AFTER that element. // key: function to extract comparison value from each array element.
function bisectRight<T>(arr: T[], val: number, key: (x: T) => number): number { let lo = 0, hi = arr.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (key(arr[mid]) <= val) lo = mid + 1; else hi = mid; } return lo; }
const assert = require('assert'); const items = [{v:1},{v:3},{v:3},{v:5}]; assert.strictEqual(bisectRight(items, 3, (x:{v:number}) => x.v), 3); assert.strictEqual(bisectRight(items, 0, (x:{v:number}) => x.v), 0); assert.strictEqual(bisectRight(items, 5, (x:{v:number}) => x.v), 4);
assert.strictEqual(bisectRight(items, 1, (x:{v:number}) => x.v), 1); assert.strictEqual(bisectRight(items, 2, (x:{v:number}) => x.v), 1); assert.strictEqual(bisectRight(items, 4, (x:{v:number}) => x.v), 3); assert.strictEqual(bisectRight(items, 6, (x:{v:number}) => x.v), 4); assert.strictEqual(bisectRight([], 1, (x:any...
low_context
46
devbench-low-context
typescript
// runLengthEncode: compress consecutive identical chars. // Format: count + sep + char for runs > 1, just char for single. // Default separator is '#'. Runs are joined with '|'.
function runLengthEncode(s: string, sep: string = '#'): string { if (!s) return ''; const parts: string[] = []; let i = 0; while (i < s.length) { let j = i; while (j < s.length && s[j] === s[i]) j++; parts.push(j - i > 1 ? (j - i) + sep + s[i] : s[i]); i = j; } return parts.join('|'); }
const assert = require('assert'); assert.strictEqual(runLengthEncode('aabbbcc'), '2#a|3#b|2#c'); assert.strictEqual(runLengthEncode('abc'), 'a|b|c'); assert.strictEqual(runLengthEncode('aabbbcc', ':'), '2:a|3:b|2:c');
assert.strictEqual(runLengthEncode(''), ''); assert.strictEqual(runLengthEncode('a'), 'a'); assert.strictEqual(runLengthEncode('aaaa'), '4#a'); assert.strictEqual(runLengthEncode('aabb'), '2#a|2#b'); assert.strictEqual(runLengthEncode('abcdd', '-'), 'a|b|c|2-d');
low_context
47
devbench-low-context
typescript
// interleave: merge two arrays by alternating elements. // If one is longer, append remaining elements at end.
function interleave<T>(a: T[], b: T[]): T[] { const result: T[] = []; const len = Math.max(a.length, b.length); for (let i = 0; i < len; i++) { if (i < a.length) result.push(a[i]); if (i < b.length) result.push(b[i]); } return result; }
const assert = require('assert'); assert.deepStrictEqual(interleave([1,2,3], [4,5,6]), [1,4,2,5,3,6]); assert.deepStrictEqual(interleave([1,2], [3,4,5]), [1,3,2,4,5]);
assert.deepStrictEqual(interleave([], []), []); assert.deepStrictEqual(interleave([1], []), [1]); assert.deepStrictEqual(interleave([], [1,2]), [1,2]); assert.deepStrictEqual(interleave(['a','b'], ['x','y','z']), ['a','x','b','y','z']); assert.deepStrictEqual(interleave([1,2,3], []), [1,2,3]);
low_context
48
devbench-low-context
typescript
// smartCapitalize: capitalize the first letter of each word, // but ONLY if the word has more than 3 characters. // Words with 1-3 chars stay lowercase. Input is lowercase.
function smartCapitalize(s: string): string { return s.split(' ').map(w => w.length > 3 ? w[0].toUpperCase() + w.slice(1) : w ).join(' '); }
const assert = require('assert'); assert.strictEqual(smartCapitalize('the big red fox'), 'the big red fox'); assert.strictEqual(smartCapitalize('a is an okay'), 'a is an Okay');
assert.strictEqual(smartCapitalize(''), ''); assert.strictEqual(smartCapitalize('hi'), 'hi'); assert.strictEqual(smartCapitalize('hello world'), 'Hello World'); assert.strictEqual(smartCapitalize('do it now run'), 'do it now run'); assert.strictEqual(smartCapitalize('i am okay fine'), 'i am Okay Fine');
low_context
49
devbench-low-context
typescript
// pick: return a new object with only the specified keys from obj. // Keys not present in obj should be skipped.
function pick<T extends Record<string, any>, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> { const result = {} as Pick<T, K>; for (const k of keys) { if (k in obj) (result as any)[k] = obj[k]; } return result; }
const assert = require('assert'); const obj = { a: 1, b: 2, c: 3, d: 4 }; assert.deepStrictEqual(pick(obj, ['a', 'c']), { a: 1, c: 3 }); assert.deepStrictEqual(pick(obj, ['b']), { b: 2 });
assert.deepStrictEqual(pick(obj, []), {}); assert.deepStrictEqual(pick(obj, ['a', 'b', 'c', 'd']), { a: 1, b: 2, c: 3, d: 4 }); assert.deepStrictEqual(pick({ x: 'hello', y: 'world' }, ['x']), { x: 'hello' });
low_context
50
devbench-low-context
typescript
// groupBy: group array elements by a key function. // Returns a Map from key to array of elements with that key. // Preserve insertion order within each group.
function groupBy<T, K>(items: T[], keyFn: (item: T) => K): Map<K, T[]> { const map = new Map<K, T[]>(); for (const item of items) { const k = keyFn(item); if (!map.has(k)) map.set(k, []); map.get(k)!.push(item); } return map; }
const assert = require('assert'); const grouped = groupBy([1,2,3,4,5,6], n => n % 2 === 0 ? 'even' : 'odd'); assert.deepStrictEqual(grouped.get('odd'), [1,3,5]); assert.deepStrictEqual(grouped.get('even'), [2,4,6]);
assert.strictEqual(groupBy([], (x: any) => x).size, 0); const g2 = groupBy(['apple','avocado','banana','blueberry'], w => w[0]); assert.deepStrictEqual(g2.get('a'), ['apple','avocado']); assert.deepStrictEqual(g2.get('b'), ['banana','blueberry']); assert.strictEqual(g2.size, 2); const g3 = groupBy([{n:'a',v:1},{n:'b',v...
low_context