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-api-usage | typescript | import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as assert from 'assert';
function atomicWriteJson(filePath: string, data: unknown): { written: number; encoding: string; flag: string } {
const json = JSON.stringify(data, null, 2);
const tmp = filePath + '.tmp.' + process.p... | `Serialize data with JSON.stringify(data, null, 2) and write to a temporary file (filePath + '.tmp.' + process.pid) using fs.writeFileSync(tmp, json, { encoding: 'utf8', mode: 0o644 }), then atomically replace the target via fs.renameSync(tmp, filePath). Returns { written, encoding, flag } where written is Buffer.byteL... | ;
assert.strictEqual(typeof (atomicWriteJson as any).doc, 'string');
const dir1 = fs.mkdtempSync(path.join(os.tmpdir(), 'ts-api-'));
const fp1 = path.join(dir1, 'out.json');
const res1 = atomicWriteJson(fp1, { a: 1 });
assert.strictEqual(res1.encoding, 'utf8');
assert.strictEqual(res1.flag, 'w');
assert.strictEqual(fs... | for (const term of [
'JSON.stringify(data, null, 2)',
'fs.writeFileSync',
'fs.renameSync',
'Buffer.byteLength',
'atomic',
'0o644',
'process.pid',
'ENOENT'
]) {
assert.ok((atomicWriteJson as any).doc.includes(term), 'doc missing: ' + term);
}
console.log('task1 assertions ok');
| api_usage |
2 | devbench-api-usage | typescript | import * as crypto from 'crypto';
import * as assert from 'assert';
function hmacHex(algorithm: string, key: string | Buffer, data: string): string {
return crypto.createHmac(algorithm, key).update(data, 'utf8').digest('hex');
}
(hmacHex as any).doc =
| `Create an HMAC using crypto.createHmac(algorithm, key), feed data with .update(data, 'utf8'), and return the hex digest via .digest('hex'). The algorithm parameter is passed directly to OpenSSL (e.g. 'sha256', 'sha512'). Throws ERR_OSSL_EVP_UNSUPPORTED for unknown algorithms and TypeError if key is neither string nor ... | ;
assert.strictEqual(typeof (hmacHex as any).doc, 'string');
const h1 = hmacHex('sha256', 'secret', 'hello');
assert.strictEqual(h1.length, 64);
assert.strictEqual(h1, crypto.createHmac('sha256', 'secret').update('hello', 'utf8').digest('hex'));
const h2 = hmacHex('sha512', 'key', 'data');
assert.strictEqual(h2.length... | for (const term of [
'crypto.createHmac',
'.update(data',
'.digest',
'hex',
'OpenSSL',
'sha256',
'sha512',
'64',
'128'
]) {
assert.ok((hmacHex as any).doc.includes(term), 'doc missing: ' + term);
}
console.log('task2 assertions ok');
| api_usage |
3 | devbench-api-usage | typescript | import * as path from 'path';
import * as assert from 'assert';
function safeRelative(from: string, to: string): string {
const absFrom = path.resolve(from);
const absTo = path.resolve(to);
const rel = path.relative(absFrom, absTo);
if (rel.startsWith('..')) {
throw new RangeError('target is outside base d... | `Resolve both from and to into absolute paths using path.resolve (which resolves against process.cwd() when given relative segments), then compute the relative path from absFrom to absTo with path.relative(absFrom, absTo). If the result starts with '..' the target is outside the base directory and a RangeError is throw... | ;
assert.strictEqual(typeof (safeRelative as any).doc, 'string');
const r1 = safeRelative('/home/user/project', '/home/user/project/src/index.ts');
assert.strictEqual(r1, 'src/index.ts');
assert.strictEqual(safeRelative('/a/b', '/a/b'), '');
let threw = false;
try { safeRelative('/a/b/c', '/a/x'); } catch (e: any) { t... | for (const term of [
'path.resolve',
'path.relative',
'process.cwd()',
'RangeError',
'right-to-left',
'empty'
]) {
assert.ok((safeRelative as any).doc.includes(term), 'doc missing: ' + term);
}
console.log('task3 assertions ok');
| api_usage |
4 | devbench-api-usage | typescript | import * as assert from 'assert';
function hexRoundTrip(input: string): { hex: string; bytes: number; recovered: string } {
const buf = Buffer.from(input, 'utf8');
const hex = buf.toString('hex');
const recovered = Buffer.from(hex, 'hex').toString('utf8');
return { hex, bytes: buf.length, recovered };
}
(hexR... | `Encode the input string to a Buffer via Buffer.from(input, 'utf8'), convert it to a hexadecimal string with buf.toString('hex') where each byte becomes two lowercase hex characters, then decode back with Buffer.from(hex, 'hex').toString('utf8'). Returns { hex, bytes, recovered } where bytes is buf.length (the byte cou... | ;
assert.strictEqual(typeof (hexRoundTrip as any).doc, 'string');
const r = hexRoundTrip('hello');
assert.strictEqual(r.hex, '68656c6c6f');
assert.strictEqual(r.bytes, 5);
assert.strictEqual(r.recovered, 'hello');
const r2 = hexRoundTrip('\u00e9');
assert.strictEqual(r2.bytes, 2);
assert.strictEqual(r2.hex.length, 4);... | for (const term of [
'Buffer.from(input',
'toString',
'hex',
'lowercase',
'two',
'buf.length',
'multi-byte',
'2 * bytes'
]) {
assert.ok((hexRoundTrip as any).doc.includes(term), 'doc missing: ' + term);
}
const r3 = hexRoundTrip('');
assert.strictEqual(r3.hex, '');
assert.strictEqual(r3.bytes, 0);
con... | api_usage |
5 | devbench-api-usage | typescript | import { pipeline, Readable, Transform, Writable } from 'stream';
import { promisify } from 'util';
import * as assert from 'assert';
const pipelineAsync = promisify(pipeline);
async function uppercasePipeline(chunks: string[]): Promise<string[]> {
const results: string[] = [];
const source = Readable.from(chunks... | `Create a Readable from chunks via Readable.from(chunks), pipe through a Transform in objectMode that calls chunk.toUpperCase() in the transform(chunk, encoding, callback) method, and collect results in a Writable's write(chunk, encoding, callback). Uses promisify(pipeline) so the returned Promise rejects on stream err... | ;
assert.strictEqual(typeof (uppercasePipeline as any).doc, 'string');
(async () => {
const result = await uppercasePipeline(['hello', 'world']);
assert.deepStrictEqual(result, ['HELLO', 'WORLD']);
const empty = await uppercasePipeline([]);
assert.deepStrictEqual(empty, []);
console.log('task5 ok');
})();
| for (const term of [
'Readable.from',
'objectMode',
'Transform',
'Writable',
'promisify(pipeline)',
'.destroy()',
'.pipe()',
'callback'
]) {
assert.ok((uppercasePipeline as any).doc.includes(term), 'doc missing: ' + term);
}
console.log('task5 assertions ok');
| api_usage |
6 | devbench-api-usage | typescript | import * as assert from 'assert';
// Create a Buffer filled with a repeating pattern.
// Buffer.alloc(size, fill, encoding) zero-fills first then fills with the pattern.
// When fill is a string and encoding is 'utf8', the fill pattern repeats to cover the buffer.
// If the fill pattern is longer than the buffer, it i... | return Buffer.alloc(size, pattern, 'utf8');
| }
const buf1 = createPatternBuffer(10, 'ab');
assert.strictEqual(buf1.toString('utf8'), 'ababababab');
assert.strictEqual(buf1.length, 10);
const buf2 = createPatternBuffer(3, 'hello');
assert.strictEqual(buf2.toString('utf8'), 'hel');
const buf3 = createPatternBuffer(5, 'x');
assert.strictEqual(buf3.toString('utf8'... | // Verify multi-byte pattern fill (UTF-8 multi-byte char)
const buf5 = createPatternBuffer(6, '\u00e9');
// \u00e9 is 2 bytes in UTF-8 (0xc3 0xa9), so 6 bytes = 3 repetitions
assert.strictEqual(buf5.toString('utf8'), '\u00e9\u00e9\u00e9');
// Single byte fills
const buf6 = createPatternBuffer(4, 'Z');
assert.strictEqu... | api_usage |
7 | devbench-api-usage | typescript | import * as crypto from 'crypto';
import * as assert from 'assert';
// Implement a timing-safe string comparison.
// crypto.timingSafeEqual requires BOTH Buffers to be the SAME length;
// if lengths differ it throws RangeError.
// To compare arbitrary strings safely: first check if lengths match,
// then use timingSaf... | const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
const lengthMatch = bufA.length === bufB.length;
if (!lengthMatch) {
return { equal: false, lengthMatch: false };
}
const equal = crypto.timingSafeEqual(bufA, bufB);
return { equal, lengthMatch: true };
| }
assert.deepStrictEqual(safeCompare('hello', 'hello'), { equal: true, lengthMatch: true });
assert.deepStrictEqual(safeCompare('hello', 'world'), { equal: false, lengthMatch: true });
assert.deepStrictEqual(safeCompare('hi', 'hello'), { equal: false, lengthMatch: false });
assert.deepStrictEqual(safeCompare('', ''), ... | // Verify timing-safe comparison with multi-byte chars
const r1 = safeCompare('caf\u00e9', 'caf\u00e9');
assert.deepStrictEqual(r1, { equal: true, lengthMatch: true });
// Same char count but different byte length
const r2 = safeCompare('\u00e9', 'e');
assert.strictEqual(r2.lengthMatch, false); // \u00e9 is 2 bytes, '... | api_usage |
8 | devbench-api-usage | typescript | import * as assert from 'assert';
// Build a URL with query parameters using the WHATWG URL API.
// URLSearchParams.append allows duplicate keys.
// URLSearchParams.set replaces all values for a key.
// The toString() of URLSearchParams encodes spaces as '+' not '%20'.
function buildUrl(
base: string,
params: Arr... | const url = new URL(base);
for (const [key, val] of params) {
url.searchParams.append(key, val);
}
for (const [key, val] of Object.entries(overrides)) {
url.searchParams.set(key, val);
}
return {
href: url.href,
search: url.search,
paramCount: Array.from(url.searchParams).length
};
| }
const r = buildUrl('https://example.com/api', [['q', 'hello world'], ['q', 'test']], { q: 'final' });
// set('q', 'final') replaces ALL existing 'q' values
assert.strictEqual(r.paramCount, 1);
assert.ok(r.href.includes('q=final'));
// spaces encoded as '+' in searchParams
const r2 = buildUrl('https://x.com', [['s', ... | // Duplicate keys with append
const r3 = buildUrl('https://x.com', [['a', '1'], ['a', '2'], ['b', '3']], {});
assert.strictEqual(r3.paramCount, 3);
// set overrides only the specified key
const r4 = buildUrl('https://x.com', [['a', '1'], ['a', '2'], ['b', '3']], { a: 'x' });
assert.strictEqual(r4.paramCount, 2); // on... | api_usage |
9 | devbench-api-usage | typescript | import * as assert from 'assert';
// Implement a type-safe pluck function that extracts a single property
// from each object in an array. The key parameter must be constrained
// to actual keys of the objects via keyof T.
| function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map(item => item[key]);
}
|
interface User { name: string; age: number; active: boolean; }
const users: User[] = [
{ name: 'Alice', age: 30, active: true },
{ name: 'Bob', age: 25, active: false },
{ name: 'Charlie', age: 35, active: true }
];
const names: string[] = pluck(users, 'name');
assert.deepStrictEqual(names, ['Alice', 'Bob', 'Ch... | // Empty array
assert.deepStrictEqual(pluck([] as User[], 'name'), []);
// Works with different object types
interface Point { x: number; y: number; label: string; }
const points: Point[] = [{ x: 1, y: 2, label: 'a' }, { x: 3, y: 4, label: 'b' }];
assert.deepStrictEqual(pluck(points, 'x'), [1, 3]);
assert.deepStrictEq... | api_usage |
10 | devbench-api-usage | typescript | import * as assert from 'assert';
// Implement a type-safe function that unwraps Promises and arrays.
// Given a value that might be a Promise<T> or T[], extract and return
// the inner type. For non-wrapped values, return as-is.
// Use TypeScript's conditional types to provide correct return types.
type UnwrapPromis... | async function unwrap<T>(value: T): Promise<UnwrapPromise<T> | UnwrapArray<T>> {
if (value instanceof Promise) {
return await value as any;
}
if (Array.isArray(value)) {
return value[0] as any;
}
return value as any;
}
|
(async () => {
// Unwrap a promise
const p = Promise.resolve(42);
const r1 = await unwrap(p);
assert.strictEqual(r1, 42);
// Unwrap an array (first element)
const arr = [10, 20, 30];
const r2 = await unwrap(arr);
assert.strictEqual(r2, 10);
// Plain value returned as-is
const r3 = await unwrap('h... | (async () => {
// Nested promise
const r4 = await unwrap(Promise.resolve('abc'));
assert.strictEqual(r4, 'abc');
// Empty array returns undefined
const r5 = await unwrap([]);
assert.strictEqual(r5, undefined);
// Number value
const r6 = await unwrap(99);
assert.strictEqual(r6, 99);
// Boolean val... | api_usage |
11 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
function parseFragmentedUrl(raw: string): {
protocol: string;
hostname: string;
pathname: string;
searchKeys: string[];
hash: string;
} {
const u = new URL(raw);
const searchKeys: string[] = [];
u.searchParams.forEach((_v, k) => searchKeys.push(k));
return {... | `Parse raw with the WHATWG URL constructor new URL(raw) and return an object containing protocol (includes trailing colon), hostname (lowercased by the URL parser), pathname (percent-encoded path), searchKeys (parameter names collected via forEach on url.searchParams in insertion order, values ignored), and hash (inclu... | ;
assert.equal(typeof parseFragmentedUrl.doc, 'string');
assert.ok(parseFragmentedUrl.doc.includes('new URL(raw)'));
assert.ok(parseFragmentedUrl.doc.includes('protocol'));
const r = parseFragmentedUrl('https://Example.COM/path?a=1&b=2#frag');
assert.equal(r.protocol, 'https:');
assert.equal(r.hostname, 'example.com'... | for (const term of [
'WHATWG URL constructor',
'trailing colon',
'lowercased by the URL parser',
'percent-encoded path',
'forEach on url.searchParams',
'insertion order',
'values ignored',
'leading # character',
'empty string if absent',
'TypeError',
'percent-decodes keys',
'never parsed as quer... | api_usage |
12 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
import * as querystring from 'querystring';
function parseQuery(qs: string, maxKeys?: number): Record<string, string | string[]> {
const parsed = querystring.parse(qs, undefined, undefined, { maxKeys: maxKeys ?? 1000 });
const result: Record<string, string | string[]> = {... | `Parse qs using querystring.parse(qs, sep, eq, options) from the legacy Node querystring module, which splits on & and = by default and returns a null-prototype object via Object.create(null).
Duplicate keys produce an array of strings; single-occurrence keys produce a plain string; keys with no = sign get empty-string... | ;
assert.equal(typeof parseQuery.doc, 'string');
assert.ok(parseQuery.doc.includes('querystring.parse'));
assert.ok(parseQuery.doc.includes('legacy'));
const r = parseQuery('a=1&b=2&a=3');
assert.deepStrictEqual(r['a'], ['1', '3']);
assert.equal(r['b'], '2');
console.log('task12 ok');
| for (const term of [
'querystring.parse(qs, sep, eq, options)',
'legacy Node querystring module',
'splits on & and =',
'null-prototype object',
'Object.create(null)',
'Duplicate keys produce an array',
'single-occurrence keys produce a plain string',
'no = sign get empty-string values',
'maxKeys optio... | api_usage |
13 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
import { EventEmitter } from 'events';
function trackEvent(emitter: EventEmitter, eventName: string): {
fire: (payload: unknown) => boolean;
history: () => unknown[];
detach: () => void;
listenerCount: () => number;
} {
const log: unknown[] = [];
const handler = (... | `Attach handler to emitter using emitter.on(eventName, handler), which registers a persistent listener that pushes each payload into an internal log array.
fire(payload) calls emitter.emit(eventName, payload) and returns true if listeners exist, false otherwise.
history() returns a shallow copy of the log array via spr... | ;
assert.equal(typeof trackEvent.doc, 'string');
assert.ok(trackEvent.doc.includes('emitter.on(eventName, handler)'));
assert.ok(trackEvent.doc.includes('removeListener'));
const ee = new EventEmitter();
const t = trackEvent(ee, 'data');
t.fire('a');
t.fire('b');
assert.deepStrictEqual(t.history(), ['a', 'b']);
asser... | for (const term of [
'persistent listener',
'pushes each payload',
'emitter.emit(eventName, payload)',
'returns true if listeners exist',
'false otherwise',
'shallow copy',
'[...log]',
'insertion order',
'exact function reference',
'other listeners for the same event intact',
'emitter.listenerCoun... | api_usage |
14 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
import { execSync } from 'child_process';
function runCommand(cmd: string, timeoutMs: number): {
stdout: string;
exitCode: number;
} {
try {
const buf = execSync(cmd, {
timeout: timeoutMs,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
}) ... | `Execute cmd synchronously via execSync(cmd, opts) with timeout set to timeoutMs milliseconds, stdio configured as ['pipe', 'pipe', 'pipe'] to capture all streams, and no encoding specified so the return value is a raw Buffer (cast via as Buffer).
On success (exit code 0), convert the Buffer to UTF-8 via buf.toString('... | ;
assert.equal(typeof runCommand.doc, 'string');
assert.ok(runCommand.doc.includes('execSync'));
assert.ok(runCommand.doc.includes('timeout'));
const r = runCommand('echo hello', 5000);
assert.equal(r.stdout, 'hello');
assert.equal(r.exitCode, 0);
const r2 = runCommand('exit 42', 5000);
assert.equal(r2.exitCode, 42);... | for (const term of [
'execSync(cmd, opts)',
"['pipe', 'pipe', 'pipe']",
'no encoding specified',
'raw Buffer',
'as Buffer',
"buf.toString('utf8')",
'trimEnd()',
'throws an Error',
'err.killed',
'terminated due to timeout',
'err.stdout',
'partial output Buffer',
'err.status',
'exit code or nu... | api_usage |
15 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
import * as util from 'util';
class TaggedValue {
constructor(public tag: string, public value: unknown) {}
[util.inspect.custom](depth: number, opts: util.InspectOptions): string {
if (depth < 0) return `[TaggedValue]`;
const inner = util.inspect(this.value, { .... | `TaggedValue defines a custom inspection via [util.inspect.custom](depth, opts), the well-known symbol that util.inspect calls instead of the default object formatter.
When depth < 0, it returns the placeholder string '[TaggedValue]' to prevent infinite recursion in deeply nested structures.
Otherwise it formats as 'Ta... | ;
assert.equal(typeof inspectTagged.doc, 'string');
assert.ok(inspectTagged.doc.includes('util.inspect.custom'));
const t = new TaggedValue('num', 42);
assert.ok(inspectTagged(t).includes('TaggedValue(num: 42)'));
const nested = new TaggedValue('outer', new TaggedValue('inner', 'hi'));
assert.ok(inspectTagged(nested,... | for (const term of [
'well-known symbol',
'instead of the default object formatter',
"depth < 0",
"'[TaggedValue]'",
'infinite recursion',
'deeply nested structures',
'TaggedValue(tag: inner)',
'recursively calling util.inspect',
'depth decremented by 1',
'opts.depth is null',
'infinite',
'color... | api_usage |
16 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
// Collect keys from a Map, but skip any key whose value is negative.
// For each skipped key, delete it from the map.
// Return the collected (non-skipped) keys in iteration order.
// IMPORTANT: Map.prototype.forEach visits keys in insertion order
// and per the ES2020 spec,... | const kept: string[] = [];
map.forEach((value, key) => {
if (value < 0) {
map.delete(key);
} else {
kept.push(key);
}
});
return kept;
| }
const m = new Map<string, number>([['a', 1], ['b', -2], ['c', 3], ['d', -4], ['e', 5]]);
const result = collectAndPrune(m);
assert.deepStrictEqual(result, ['a', 'c', 'e']);
assert.equal(m.size, 3);
assert.ok(!m.has('b'));
assert.ok(!m.has('d'));
console.log('task16 ok');
| // Test with all negative
const m2 = new Map<string, number>([['x', -1], ['y', -2]]);
const r2 = collectAndPrune(m2);
assert.deepStrictEqual(r2, []);
assert.equal(m2.size, 0);
// Test with all positive
const m3 = new Map<string, number>([['p', 10], ['q', 20]]);
const r3 = collectAndPrune(m3);
assert.deepStrictEqual(r3... | api_usage |
17 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
// Sort an array of strings using Intl.Collator with specific options:
// - locale: 'de' (German)
// - sensitivity: 'base' (ignore case and accents)
// - numeric: true (sort "file2" before "file10")
// Return a NEW sorted array (do not mutate the input).
// Also return the nu... | const collator = new Intl.Collator('de', {
sensitivity: 'base',
numeric: true,
});
const sorted = [...items].sort(collator.compare);
let groups = 0;
for (let i = 0; i < sorted.length; i++) {
if (i === 0 || collator.compare(sorted[i], sorted[i - 1]) !== 0) {
groups++;
}
}
return { sor... | }
const r = germanSort(['file10', 'file2', 'file1', 'FILE1']);
assert.deepStrictEqual(r.sorted, ['file1', 'FILE1', 'file2', 'file10']);
assert.equal(r.uniqueGroups, 3); // file1/FILE1 are same group
console.log('task17 ok');
| // Empty array
const r2 = germanSort([]);
assert.deepStrictEqual(r2.sorted, []);
assert.equal(r2.uniqueGroups, 0);
// All same under base sensitivity
const r3 = germanSort(['a', 'A', 'à', 'À']);
assert.equal(r3.uniqueGroups, 1);
assert.equal(r3.sorted.length, 4);
// Numeric sorting
const r4 = germanSort(['item20', 'i... | api_usage |
18 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
// Extract all key=value pairs from a string using RegExp named groups.
// Pattern: word characters for key, then =, then either a double-quoted
// string (capture content without quotes) or unquoted non-space chars.
// Use String.prototype.matchAll with a global RegExp.
// R... | const re = /(?<key>\w+)=(?:"(?<quoted>[^"]*)"|(?<unquoted>\S+))/g;
const results: Array<{ key: string; value: string; index: number }> = [];
for (const m of input.matchAll(re)) {
results.push({
key: m.groups!.key,
value: m.groups!.quoted ?? m.groups!.unquoted ?? '',
index: m.index!,
});
... | }
const r = extractPairs('name=Alice age=30 msg="hello world"');
assert.equal(r.length, 3);
assert.equal(r[0].key, 'name');
assert.equal(r[0].value, 'Alice');
assert.equal(r[0].index, 0);
assert.equal(r[2].key, 'msg');
assert.equal(r[2].value, 'hello world');
console.log('task18 ok');
| // Empty string
assert.deepStrictEqual(extractPairs(''), []);
// Only quoted values
const r2 = extractPairs('a="1" b="2 3"');
assert.equal(r2.length, 2);
assert.equal(r2[0].value, '1');
assert.equal(r2[1].value, '2 3');
// Mixed with special chars in unquoted
const r3 = extractPairs('path=/usr/bin x="y"');
assert.equ... | api_usage |
19 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
type TextResult = { kind: 'text'; content: string };
type ErrorResult = { kind: 'error'; code: number; message: string };
type PendingResult = { kind: 'pending'; retryAfterMs: number };
type ApiResult = TextResult | ErrorResult | PendingResult;
// Process a batch of ApiResul... | const texts: string[] = [];
const pendingDelays: number[] = [];
for (const r of results) {
if (r.kind === 'text') { texts.push(r.content); }
else if (r.kind === 'error') {
if (r.code >= 500) throw new Error(`server error: ${r.message}`);
} else if (r.kind === 'pending') { pendingDelays.push(r.re... | }
const batch: ApiResult[] = [
{ kind: 'text', content: 'hello' },
{ kind: 'error', code: 404, message: 'not found' },
{ kind: 'pending', retryAfterMs: 1000 },
{ kind: 'text', content: 'world' },
];
const r = processBatch(batch);
assert.deepStrictEqual(r.texts, ['hello', 'world']);
assert.deepStrictEqual(r.pen... | // Empty batch
const r2 = processBatch([]);
assert.deepStrictEqual(r2.texts, []);
assert.deepStrictEqual(r2.pendingDelays, []);
// All client errors (< 500) skipped silently
const r3 = processBatch([
{ kind: 'error', code: 400, message: 'bad' },
{ kind: 'error', code: 499, message: 'too many' },
{ kind: 'text', ... | api_usage |
20 | devbench-api-usage | typescript | import { strict as assert } from 'assert';
// Given an object and an array of keys to pick, return a new object
// containing ONLY those keys (like TypeScript's Pick<T, K> at runtime).
// If a key doesn't exist on the source, include it with value undefined.
// Additionally return a 'rest' object containing all OTHER ... | const picked: Record<string, unknown> = {};
const rest: Record<string, unknown> = {};
const keySet = new Set<string | number | symbol>(keys);
for (const key of keySet) {
picked[key as string] = source[key as string];
}
for (const key of Object.keys(source)) {
if (!keySet.has(key)) {
rest[key] ... | }
const src = { a: 1, b: 2, c: 3, d: 4 };
const { picked, rest } = pickAndRest(src, ['a', 'c']);
assert.deepStrictEqual(picked, { a: 1, c: 3 });
assert.deepStrictEqual(rest, { b: 2, d: 4 });
// Verify no shared references
(picked as any).a = 999;
assert.equal(src.a, 1);
console.log('task20 ok');
| // Missing keys get undefined
const r2 = pickAndRest({ x: 10 } as Record<string, unknown>, ['x', 'y']);
assert.equal(r2.picked['x'], 10);
assert.equal(r2.picked['y'], undefined);
assert.ok('y' in r2.picked);
assert.deepStrictEqual(r2.rest, {});
// Empty keys array
const r3 = pickAndRest({ a: 1, b: 2 }, []);
assert.dee... | api_usage |
21 | devbench-api-usage | typescript | import * as os from 'os';
import * as assert from 'assert';
function cpuModelSummary(): Record<string, number> {
const cpus = os.cpus();
const counts: Record<string, number> = {};
for (const cpu of cpus) {
counts[cpu.model] = (counts[cpu.model] || 0) + 1;
}
return counts;
}
// Fill in precise API docume... | `Call os.cpus() which returns an array of objects each having model, speed, and times properties; this function only reads the model string property from each element.
Aggregate into a Record<string, number> where each key is a distinct cpu.model string and each value is the count of logical CPUs reporting that model.
... | ;
assert.strictEqual(typeof (cpuModelSummary as any).doc, 'string');
assert.ok((cpuModelSummary as any).doc.includes('os.cpus()'));
assert.ok((cpuModelSummary as any).doc.includes('model'));
const result = cpuModelSummary();
const cpus = os.cpus();
let total = 0;
for (const v of Object.values(result)) total += v;
ass... | for (const term of [
'model, speed, and times properties',
'only reads the model string property',
'Record<string, number>',
'distinct cpu.model string',
'count of logical CPUs',
'single-model machine',
'exactly one key',
'os.cpus().length',
'never filters or transforms the model string'
]) {
assert... | api_usage |
22 | devbench-api-usage | typescript | import * as zlib from 'zlib';
import * as assert from 'assert';
function compressAndVerify(input: string): { compressed: Buffer; ratio: number } {
const buf = Buffer.from(input, 'utf-8');
const compressed = zlib.deflateSync(buf);
const decompressed = zlib.inflateSync(compressed);
if (!buf.equals(decompressed))... | `Encode the input string into a Buffer with Buffer.from(input, 'utf-8'), compress it with zlib.deflateSync which returns a Buffer containing raw deflate data with a zlib header, then decompress with zlib.inflateSync.
Verify the roundtrip with buf.equals(decompressed) which performs a byte-by-byte Buffer comparison and ... | ;
assert.strictEqual(typeof (compressAndVerify as any).doc, 'string');
assert.ok((compressAndVerify as any).doc.includes('zlib.deflateSync'));
assert.ok((compressAndVerify as any).doc.includes('zlib.inflateSync'));
assert.ok((compressAndVerify as any).doc.includes('buf.equals'));
const r = compressAndVerify('hello wo... | for (const term of [
"Buffer.from(input, 'utf-8')",
'raw deflate data with a zlib header',
'byte-by-byte Buffer comparison',
"throws an Error with message 'roundtrip mismatch'",
'compressed.length / buf.length',
'ratio can exceed 1.0',
'zlib header overhead dominates'
]) {
assert.ok((compressAndVerify a... | api_usage |
23 | devbench-api-usage | typescript | import * as http from 'http';
import * as assert from 'assert';
function statusTextLookup(code: number): string | undefined {
return http.STATUS_CODES[code];
}
// Fill in precise API documentation for statusTextLookup.
// The executable implementation above is the source of truth.
(statusTextLookup as any).doc =
| `Look up the standard HTTP reason phrase for code by indexing into http.STATUS_CODES, a plain object whose keys are numeric status code strings and whose values are the English reason phrases defined by IANA.
Return the string reason phrase if the code exists as a key, or undefined if the code is not a recognized HTTP ... | ;
assert.strictEqual(typeof (statusTextLookup as any).doc, 'string');
assert.ok((statusTextLookup as any).doc.includes('http.STATUS_CODES'));
assert.strictEqual(statusTextLookup(200), 'OK');
assert.strictEqual(statusTextLookup(404), 'Not Found');
assert.strictEqual(statusTextLookup(999), undefined);
console.log('task... | for (const term of [
'reason phrase',
'numeric status code strings',
'English reason phrases defined by IANA',
'undefined if the code is not a recognized HTTP status code',
'coerces the number to a string key',
'no validation, caching, or case transformation',
'single-property read',
'built-in Node.js h... | api_usage |
24 | devbench-api-usage | typescript | import * as net from 'net';
import * as assert from 'assert';
function classifyIP(addr: string): 'IPv4' | 'IPv6' | 'invalid' {
const version = net.isIP(addr);
if (version === 4) return 'IPv4';
if (version === 6) return 'IPv6';
return 'invalid';
}
// Fill in precise API documentation for classifyIP.
// The exe... | `Call net.isIP(addr) which returns the integer 4 for valid IPv4 addresses, 6 for valid IPv6 addresses, or 0 for strings that are neither; the function does not perform DNS resolution or hostname lookup.
Map the return value: 4 yields the string literal 'IPv4', 6 yields 'IPv6', and 0 yields 'invalid'; the comparison use... | ;
assert.strictEqual(typeof (classifyIP as any).doc, 'string');
assert.ok((classifyIP as any).doc.includes('net.isIP'));
assert.strictEqual(classifyIP('127.0.0.1'), 'IPv4');
assert.strictEqual(classifyIP('::1'), 'IPv6');
assert.strictEqual(classifyIP('not-an-ip'), 'invalid');
console.log('task24 ok');
| for (const term of [
'returns the integer 4',
'6 for valid IPv6 addresses',
'0 for strings that are neither',
'does not perform DNS resolution or hostname lookup',
"4 yields the string literal 'IPv4'",
"6 yields 'IPv6'",
"0 yields 'invalid'",
'strict equality against the numeric constants',
'net.isIP ... | api_usage |
25 | devbench-api-usage | typescript | import * as dns from 'dns';
import * as assert from 'assert';
function dnsServerCount(): { servers: string[]; count: number; hasIPv6: boolean } {
const servers = dns.getServers();
const hasIPv6 = servers.some(s => s.includes(':'));
return { servers, count: servers.length, hasIPv6 };
}
// Fill in precise API doc... | `Call dns.getServers() which returns a new string array of IP addresses currently configured for DNS resolution, formatted as RFC 5952 strings; IPv6 addresses may include a port suffix in the format '[ip]:port'.
Determine hasIPv6 by calling servers.some(s => s.includes(':')) which checks whether any server string conta... | ;
assert.strictEqual(typeof (dnsServerCount as any).doc, 'string');
assert.ok((dnsServerCount as any).doc.includes('dns.getServers()'));
const info = dnsServerCount();
assert.ok(Array.isArray(info.servers));
assert.strictEqual(info.count, info.servers.length);
assert.strictEqual(typeof info.hasIPv6, 'boolean');
conso... | for (const term of [
'new string array',
'IP addresses currently configured for DNS resolution',
'RFC 5952 strings',
"'[ip]:port'",
"servers.some(s => s.includes(':'))",
'colon character',
'colons are part of the IPv6 notation',
'servers.length',
'at least 1 on a properly configured system'
]) {
ass... | api_usage |
26 | devbench-api-usage | typescript | import * as assert from 'assert';
interface Item { name: string; priority: number; insertOrder: number; }
function stableSortByPriority(items: Item[]): Item[] {
| return items.slice().sort((a, b) => {
const diff = a.priority - b.priority;
if (diff !== 0) return diff;
return a.insertOrder - b.insertOrder;
});
| }
const data: Item[] = [
{ name: 'c', priority: 2, insertOrder: 0 },
{ name: 'a', priority: 1, insertOrder: 1 },
{ name: 'b', priority: 2, insertOrder: 2 },
{ name: 'd', priority: 1, insertOrder: 3 },
];
const sorted = stableSortByPriority(data);
assert.strictEqual(sorted[0].name, 'a');
assert.strictEqual(sort... | // Equal-priority items must preserve insertOrder ordering
const big: Item[] = [];
for (let i = 99; i >= 0; i--) {
big.push({ name: String(i), priority: i % 3, insertOrder: 99 - i });
}
const bigSorted = stableSortByPriority(big);
for (let i = 1; i < bigSorted.length; i++) {
if (bigSorted[i].priority === bigSorted[... | api_usage |
27 | devbench-api-usage | typescript | import * as assert from 'assert';
interface SettledSummary {
fulfilled: number;
rejected: number;
values: unknown[];
reasons: unknown[];
}
async function summarizeSettled(promises: Promise<unknown>[]): Promise<SettledSummary> {
| const results = await Promise.allSettled(promises);
const summary: SettledSummary = { fulfilled: 0, rejected: 0, values: [], reasons: [] };
for (const r of results) {
if (r.status === 'fulfilled') {
summary.fulfilled++;
summary.values.push(r.value);
} else {
summary.rejected++;
sum... | }
(async () => {
const s = await summarizeSettled([
Promise.resolve(42),
Promise.reject('err1'),
Promise.resolve('ok'),
Promise.reject(new Error('err2')),
]);
assert.strictEqual(s.fulfilled, 2);
assert.strictEqual(s.rejected, 2);
assert.deepStrictEqual(s.values, [42, 'ok']);
assert.strictEq... | (async () => {
// All fulfilled
const all = await summarizeSettled([Promise.resolve(1), Promise.resolve(2)]);
assert.strictEqual(all.fulfilled, 2);
assert.strictEqual(all.rejected, 0);
assert.deepStrictEqual(all.values, [1, 2]);
assert.deepStrictEqual(all.reasons, []);
// All rejected
const none = awai... | api_usage |
28 | devbench-api-usage | typescript | import * as assert from 'assert';
class ValidationError extends RangeError {
public readonly field: string;
constructor(field: string, message: string) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function validateAge(input: unknown): number {
| if (typeof input !== 'number') {
throw new TypeError(`Expected number but received ${typeof input}`);
}
if (!Number.isFinite(input)) {
throw new TypeError(`Expected finite number but received ${input}`);
}
if (input < 0 || input > 150) {
throw new ValidationError('age', `Age must be between 0 and ... | }
assert.strictEqual(validateAge(25), 25);
assert.strictEqual(validateAge(25.9), 25);
assert.strictEqual(validateAge(0), 0);
assert.strictEqual(validateAge(150), 150);
assert.throws(() => validateAge('25'), TypeError);
assert.throws(() => validateAge(null), TypeError);
assert.throws(() => validateAge(NaN), TypeError)... | // TypeError for non-number types
for (const bad of [undefined, true, {}, [], '10', Symbol()]) {
try {
validateAge(bad);
assert.fail('should have thrown');
} catch (e: any) {
assert.ok(e instanceof TypeError, `Expected TypeError for ${String(bad)}`);
assert.ok(e.message.includes(typeof bad), 'messag... | api_usage |
29 | devbench-api-usage | typescript | import * as assert from 'assert';
function createCountdown(from: number, onTick: (n: number) => void, onDone: () => void): { cancel: () => void } {
| let current = from;
const id = setInterval(() => {
if (current <= 0) {
clearInterval(id);
onDone();
return;
}
onTick(current);
current--;
}, 0);
return {
cancel: () => {
clearInterval(id);
}
};
| }
// Test basic countdown
const ticks: number[] = [];
let done = false;
const cd = createCountdown(3, (n) => ticks.push(n), () => { done = true; });
setTimeout(() => {
assert.deepStrictEqual(ticks, [3, 2, 1]);
assert.strictEqual(done, true);
console.log('task29 ok');
}, 100);
| // Test cancel
setTimeout(() => {
const ticks2: number[] = [];
let done2 = false;
const cd2 = createCountdown(10, (n) => {
ticks2.push(n);
if (n === 8) cd2.cancel();
}, () => { done2 = true; });
setTimeout(() => {
assert.deepStrictEqual(ticks2, [10, 9, 8]);
assert.strictEqual(done2, false);
... | api_usage |
30 | devbench-api-usage | typescript | import * as assert from 'assert';
class DateRange {
constructor(public start: Date, public end: Date) {}
toJSON(): { __type: string; start: string; end: string } {
return {
__type: 'DateRange',
start: this.start.toISOString(),
end: this.end.toISOString(),
};
}
}
function serializeDate... | return JSON.stringify(range);
| }
function deserializeDateRange(json: string): DateRange {
const parsed = JSON.parse(json, (key, value) => {
if (value && value.__type === 'DateRange') {
return new DateRange(new Date(value.start), new Date(value.end));
}
return value;
});
return parsed;
}
const d1 = new Date('2024-01-01T00:00... | // toJSON is called automatically by JSON.stringify
const r = new DateRange(new Date('2020-06-15T12:00:00Z'), new Date('2020-06-16T12:00:00Z'));
const s = serializeDateRange(r);
const p = JSON.parse(s);
assert.strictEqual(Object.keys(p).length, 3);
assert.strictEqual(p.__type, 'DateRange');
assert.ok(!p.hasOwnProperty(... | api_usage |
31 | devbench-api-usage | typescript | import * as assert from 'assert';
function matchReport(actual: unknown, expected: unknown): {
match: boolean;
errorCode: string | null;
operatorUsed: string | null;
} {
try {
assert.deepStrictEqual(actual, expected);
return { match: true, errorCode: null, operatorUsed: null };
} catch (e: any) {
... | `Wrap assert.deepStrictEqual(actual, expected) in a try/catch and return match: true with null errorCode and operatorUsed when it does not throw.
When Node throws an AssertionError, return match: false with e.code set to 'ERR_ASSERTION' and e.operator set to 'deepStrictEqual'.
Node deepStrictEqual uses Object.is for pr... | ;
assert.strictEqual(typeof matchReport.doc, 'string');
assert.ok(matchReport.doc.includes('assert.deepStrictEqual(actual, expected)'));
assert.ok(matchReport.doc.includes('AssertionError'));
assert.ok(matchReport.doc.includes('Object.is'));
assert.deepStrictEqual(matchReport(NaN, NaN), { match: true, errorCode: null... | for (const term of [
'does not throw',
'ERR_ASSERTION',
'deepStrictEqual',
'Object.is',
'NaN equals NaN',
'+0 differs from -0',
'Object.getPrototypeOf',
'own enumerable string-keyed properties',
'Map/Set entries',
'SameValueZero'
]) {
assert.ok(matchReport.doc.includes(term), 'doc missing: ' + ter... | api_usage |
32 | devbench-api-usage | typescript | import * as assert from 'assert';
function profileBlock(fn: () => void): {
elapsedNs: bigint;
heapUsedDelta: number;
rssAtStart: number;
} {
const rssAtStart = process.memoryUsage().rss;
const heapBefore = process.memoryUsage().heapUsed;
const t0 = process.hrtime.bigint();
fn();
const t1 = process.hrti... | `Execute fn synchronously between two process.hrtime.bigint() calls and return the elapsed wall-clock time in nanoseconds as a BigInt.
process.hrtime.bigint() returns the current high-resolution real time as a single BigInt in nanoseconds, unlike the legacy process.hrtime() which returns a [seconds, nanoseconds] tuple.... | ;
assert.strictEqual(typeof profileBlock.doc, 'string');
assert.ok(profileBlock.doc.includes('process.hrtime.bigint()'));
assert.ok(profileBlock.doc.includes('process.memoryUsage()'));
const result = profileBlock(() => { let s = 0; for (let i = 0; i < 1000; i++) s += i; });
assert.strictEqual(typeof result.elapsedNs,... | for (const term of [
'wall-clock time in nanoseconds',
'BigInt',
'high-resolution real time',
'single BigInt in nanoseconds',
'legacy process.hrtime()',
'[seconds, nanoseconds] tuple',
'resident set size in bytes',
'heapUsed',
'V8 heap memory',
'JavaScript objects in bytes'
]) {
assert.ok(profileB... | api_usage |
33 | devbench-api-usage | typescript | import * as assert from 'assert';
import { performance, PerformanceObserver } from 'perf_hooks';
function measureWithObserver(label: string, fn: () => void): Promise<{
durationMs: number;
entryType: string;
observedCount: number;
}> {
return new Promise((resolve) => {
let observedCount = 0;
const obs =... | `Create a PerformanceObserver that listens for 'measure' entries via obs.observe({ entryTypes: ['measure'] }), then bracket fn() with performance.mark(label+'-start') and performance.mark(label+'-end').
Call performance.measure(label, startMark, endMark) to create a PerformanceMeasure entry whose duration property is t... | ;
assert.strictEqual(typeof measureWithObserver.doc, 'string');
assert.ok(measureWithObserver.doc.includes('PerformanceObserver'));
assert.ok(measureWithObserver.doc.includes('performance.mark'));
assert.ok(measureWithObserver.doc.includes('performance.measure'));
(async () => {
const r = await measureWithObserver(... | for (const term of [
"entryTypes: ['measure']",
'performance.mark',
'performance.measure(label, startMark, endMark)',
'PerformanceMeasure',
'elapsed milliseconds between the two marks',
"entryType is always the string 'measure'",
'PerformanceObserverEntryList',
'list.getEntries()',
'PerformanceEntry',... | api_usage |
34 | devbench-api-usage | typescript | import * as assert from 'assert';
function diagnosticReport(items: Array<{ name: string; value: number }>): {
tableLabel: string;
countLabel: string;
timeLabel: string;
itemCount: number;
} {
const label = 'diag-' + Date.now();
console.time(label);
console.table(items, ['name', 'value']);
for (const it... | `Call console.time(label) to start a timer, then console.table(items, ['name', 'value']) to print items as a table restricted to the columns 'name' and 'value' via the optional second argument.
Loop over items calling console.count(label) which increments and prints an internal counter scoped to that label string, then... | ;
assert.strictEqual(typeof diagnosticReport.doc, 'string');
assert.ok(diagnosticReport.doc.includes('console.time(label)'));
assert.ok(diagnosticReport.doc.includes('console.table'));
assert.ok(diagnosticReport.doc.includes('console.count'));
const r = diagnosticReport([{ name: 'a', value: 1 }, { name: 'b', value: 2... | for (const term of [
"console.table(items, ['name', 'value'])",
'optional second argument',
'console.count(label)',
'internal counter scoped to that label',
'console.timeLog(label',
'without stopping the timer',
'extra data arguments after the label',
'console.countReset(label)',
'reset the counter fo... | api_usage |
35 | devbench-api-usage | typescript | import * as assert from 'assert';
import { StringDecoder } from 'string_decoder';
function streamDecode(chunks: Buffer[], encoding: BufferEncoding = 'utf8'): {
result: string;
hadPartial: boolean;
flushed: string;
} {
const decoder = new StringDecoder(encoding);
let result = '';
let hadPartial = false;
f... | `Create new StringDecoder(encoding) and feed each Buffer chunk through decoder.write(chunk), which returns any complete characters decoded so far while buffering incomplete trailing multi-byte sequences internally.
Set hadPartial to true when a non-final chunk's decoded output has fewer bytes (measured by Buffer.byteLe... | ;
assert.strictEqual(typeof streamDecode.doc, 'string');
assert.ok(streamDecode.doc.includes('new StringDecoder(encoding)'));
assert.ok(streamDecode.doc.includes('decoder.write'));
assert.ok(streamDecode.doc.includes('decoder.end()'));
const simple = streamDecode([Buffer.from('Hello'), Buffer.from(' World')]);
assert... | for (const term of [
'incomplete trailing multi-byte sequences',
'buffering',
'Buffer.byteLength',
'decoder retained trailing bytes',
'flush any remaining buffered bytes',
'replacement character U+FFFD',
'incomplete sequence',
'flushed string separately',
'concatenated result'
]) {
assert.ok(streamD... | api_usage |
36 | devbench-api-usage | typescript | import * as assert from 'assert';
// Build a function that demonstrates TypedArray.from() with a mapping function
// and the buffer-sharing behavior of subarray() vs slice().
//
// Requirements:
// 1. Create a Uint8Array from an iterable using Uint8Array.from() with a mapFn
// that doubles each value and clamps to ... | function typedArrayEdgeCases(values: number[]): {
original: Uint8Array;
subMutated: boolean;
sliceSafe: boolean;
sharesSameBuffer: boolean;
} {
const arr = Uint8Array.from(values, (v) => Math.min(v * 2, 255));
const sub = arr.subarray(1, 3);
const slc = arr.slice(1, 3);
const origBefore = arr[1];
sub[... |
const r1 = typedArrayEdgeCases([10, 20, 30, 40, 50]);
assert.deepStrictEqual([...r1.original], [20, 40, 60, 80, 100]);
assert.strictEqual(r1.subMutated, true);
assert.strictEqual(r1.sliceSafe, true);
assert.strictEqual(r1.sharesSameBuffer, true);
// Clamping test
const r2 = typedArrayEdgeCases([100, 130, 200]);
asser... | // Verify Uint8Array.from mapFn behavior
const r3 = typedArrayEdgeCases([0, 1, 127, 128]);
assert.deepStrictEqual([...r3.original], [0, 2, 254, 255]);
assert.strictEqual(r3.subMutated, true);
assert.strictEqual(r3.sliceSafe, true);
assert.strictEqual(r3.sharesSameBuffer, true);
// Single element
const r4 = typedArrayE... | api_usage |
37 | devbench-api-usage | typescript | import * as assert from 'assert';
// Build a function that uses DataView to read/write values with explicit endianness.
//
// Requirements:
// 1. Create an ArrayBuffer of 16 bytes
// 2. Using a DataView, write the following at the given offsets:
// - offset 0: Float32 value 3.14 in BIG endian (littleEndian = false)... | function dataViewEndianness(): {
f32: number;
u16: number;
i32: number;
f64: number;
u16BigEndian: number;
} {
const buf = new ArrayBuffer(18);
const view = new DataView(buf);
view.setFloat32(0, 3.14, false);
view.setUint16(4, 0xCAFE, true);
view.setInt32(6, -1, false);
view.setFloat64(10, 2.718, ... |
const r = dataViewEndianness();
assert.ok(Math.abs(r.f32 - 3.14) < 0.001);
assert.strictEqual(r.u16, 0xCAFE);
assert.strictEqual(r.i32, -1);
assert.ok(Math.abs(r.f64 - 2.718) < 0.0001);
// Reading 0xCAFE written in LE as BE gives 0xFECA
assert.strictEqual(r.u16BigEndian, 0xFECA);
console.log('task37 ok');
| // Verify exact byte layout by reading raw bytes
const buf2 = new ArrayBuffer(18);
const dv2 = new DataView(buf2);
dv2.setUint16(4, 0xCAFE, true);
// LE writes FE at offset 4, CA at offset 5
assert.strictEqual(dv2.getUint8(4), 0xFE);
assert.strictEqual(dv2.getUint8(5), 0xCA);
// Int32 -1 in BE is 0xFFFFFFFF
dv2.setInt... | api_usage |
38 | devbench-api-usage | typescript | import * as assert from 'assert';
// Build a function demonstrating Atomics operations on a SharedArrayBuffer.
//
// Requirements:
// 1. Create a SharedArrayBuffer with space for 4 Int32 values
// 2. Create an Int32Array view on it
// 3. Use Atomics.store to set index 0 to 42 (returns the stored value)
// 4. Use Atomi... | function atomicsDemo(): {
storeReturn: number;
loaded: number;
addReturn: number;
afterAdd: number;
cmpxReturn: number;
afterCmpx: number;
exchReturn: number;
afterExch: number;
orReturn: number;
afterOr: number;
} {
const sab = new SharedArrayBuffer(16);
const arr = new Int32Array(sab);
const... |
const r = atomicsDemo();
assert.strictEqual(r.storeReturn, 42);
assert.strictEqual(r.loaded, 42);
assert.strictEqual(r.addReturn, 42); // OLD value before add
assert.strictEqual(r.afterAdd, 50); // 42 + 8
assert.strictEqual(r.cmpxReturn, 0); // OLD value (was 0, matched, so set to 100)
assert.strictEqual(r.afte... | // Atomics.or returns OLD value before OR
assert.strictEqual(r.orReturn, 0xF0);
// 0xF0 | 0x0F = 0xFF
assert.strictEqual(r.afterOr, 0xFF);
// Verify Atomics.compareExchange when condition is NOT met
const sab2 = new SharedArrayBuffer(4);
const arr2 = new Int32Array(sab2);
Atomics.store(arr2, 0, 5);
const cmpResult = A... | api_usage |
39 | devbench-api-usage | typescript | import * as assert from 'assert';
// Build a validation proxy factory that:
// 1. Uses a Proxy with 'set' trap to validate property assignments
// 2. The 'set' trap must use Reflect.set() and return its boolean result
// 3. Properties starting with '_' are read-only (set trap returns false)
// 4. Numeric properties mu... | function createValidationProxy<T extends Record<string, any>>(target: T): {
proxy: T;
getRejections: () => string[];
} {
const rejections: string[] = [];
const handler: ProxyHandler<T> = {
set(obj, prop, value, receiver) {
const key = String(prop);
if (key.startsWith('_')) {
rejections.p... |
const target: Record<string, any> = { name: 'test', _id: 1, count: 0 };
const { proxy, getRejections } = createValidationProxy(target);
proxy.name = 'updated';
assert.strictEqual(proxy.name, 'updated');
// Read-only rejection
assert.strictEqual(Reflect.set(proxy, '_id', 999), false);
assert.strictEqual(proxy._id, 1);... | const rej = getRejections();
assert.ok(rej.includes('readonly:_id'));
assert.ok(rej.includes('non-finite:count'));
assert.ok(rej.filter(r => r.startsWith('non-finite')).length >= 2);
// Verify Reflect.set through proxy respects the trap
const target2: Record<string, any> = { x: 0, _y: 0 };
const { proxy: p2, getReject... | api_usage |
40 | devbench-api-usage | typescript | import * as assert from 'assert';
// Build a class RangeSet that uses well-known symbols:
//
// 1. Symbol.iterator: yield all integers in [start, end) — half-open range
// 2. Symbol.toPrimitive:
// - hint 'number' → return the count of integers (end - start)
// - hint 'string' → return "RangeSet(start..end)"
// ... | class RangeSet {
readonly start: number;
readonly end: number;
constructor(start: number, end: number) {
this.start = start;
this.end = end;
}
*[Symbol.iterator](): Generator<number> {
for (let i = this.start; i < this.end; i++) yield i;
}
[Symbol.toPrimitive](hint: string): number | string... |
const rs = new RangeSet(3, 7);
assert.deepStrictEqual([...rs], [3, 4, 5, 6]);
assert.strictEqual(Number(rs), 4);
assert.strictEqual(`${rs}`, 'RangeSet(3..7)');
assert.strictEqual(Object.prototype.toString.call(rs), '[object RangeSet]');
const rs2 = new RangeSet(0, 3);
assert.deepStrictEqual([...rs2], [0, 1, 2]);
asse... | // Empty range
const empty = new RangeSet(5, 5);
assert.deepStrictEqual([...empty], []);
assert.strictEqual(Number(empty), 0);
assert.strictEqual(`${empty}`, 'RangeSet(5..5)');
// toPrimitive 'default' hint (used in == and +)
const rs3 = new RangeSet(0, 10);
assert.strictEqual(Number(rs3) + 0, 10);
// toStringTag
ass... | api_usage |
41 | devbench-api-usage | typescript | import * as assert from 'assert';
// Buffer encoding utility library
// Converts strings between encodings via Buffer intermediary
// Demonstrate: Buffer.from interprets the string AS that encoding
// Buffer.from('AQID', 'base64') -> <Buffer 01 02 03> (decodes base64)
// .toString('hex') -> '010203'
const demo1 = Bu... | function convertEncoding(input: string, fromEnc: BufferEncoding, toEnc: BufferEncoding): string {
return Buffer.from(input, fromEnc).toString(toEnc);
}
| // Convert base64 to hex
const r1 = convertEncoding('AQID', 'base64', 'hex');
assert.strictEqual(r1, '010203');
// Convert hex to utf8
const r2 = convertEncoding('48656c6c6f', 'hex', 'utf8');
assert.strictEqual(r2, 'Hello');
// Convert utf8 to base64
const r3 = convertEncoding('Hello', 'utf8', 'base64');
assert.stric... | // Base64 to utf8
const a1 = convertEncoding('SGVsbG8gV29ybGQ=', 'base64', 'utf8');
assert.strictEqual(a1, 'Hello World');
// utf8 to hex
const a2 = convertEncoding('AB', 'utf8', 'hex');
assert.strictEqual(a2, '4142');
// hex to base64
const a3 = convertEncoding('4142', 'hex', 'base64');
assert.strictEqual(a3, 'QUI='... | api_usage |
42 | devbench-api-usage | typescript | import * as assert from 'assert';
// Date arithmetic library with CUSTOM business rules:
// - "Business months" are 1-indexed (January=1, December=12)
// - Internally converts to JS Date (0-indexed months)
// - Returns results in business month format (1-indexed)
interface DateInfo {
year: number;
month: numb... | function getDateInfo(year: number, businessMonth: number, day: number): DateInfo {
// Convert 1-indexed business month to 0-indexed JS month
const date = new Date(year, businessMonth - 1, day);
// Days in this month: create date for day 0 of NEXT month
const daysInMonth = new Date(year, businessMonth, 0... | // January 1, 2024 = Monday
const d1 = getDateInfo(2024, 1, 1);
assert.strictEqual(d1.dayOfWeek, 'Monday');
assert.strictEqual(d1.month, 1);
assert.strictEqual(d1.daysInMonth, 31);
// February 2024 (leap year) = 29 days
const d2 = getDateInfo(2024, 2, 15);
assert.strictEqual(d2.daysInMonth, 29);
assert.strictEqual(d2.... | // February 2023 (non-leap year) = 28 days
const a1 = getDateInfo(2023, 2, 1);
assert.strictEqual(a1.daysInMonth, 28);
// April has 30 days
const a2 = getDateInfo(2024, 4, 10);
assert.strictEqual(a2.daysInMonth, 30);
// July 4, 2024 = Thursday
const a3 = getDateInfo(2024, 7, 4);
assert.strictEqual(a3.dayOfWeek, 'Thur... | api_usage |
43 | devbench-api-usage | typescript | import * as assert from 'assert';
// Numeric parsing library with STRICT validation
// Uses Number.isFinite (not global isFinite) and Number.isNaN (not global isNaN)
//
// KEY DIFFERENCES (from MDN):
// - global isNaN('hello') => true (coerces string, then checks)
// - Number.isNaN('hello') => false (no coercion, 'he... | function strictParse(input: unknown, method: 'int' | 'float', radix?: number): ParseResult {
const originalType = typeof input;
let value: number;
if (method === 'int') {
value = parseInt(String(input), radix ?? 10);
} else {
value = parseFloat(String(input));
}
return {
... | // Basic integer parsing
const r1 = strictParse('42', 'int');
assert.strictEqual(r1.value, 42);
assert.strictEqual(r1.isValid, true);
assert.strictEqual(r1.originalType, 'string');
// Hex parsing with radix
const r2 = strictParse('ff', 'int', 16);
assert.strictEqual(r2.value, 255);
assert.strictEqual(r2.isValid, true)... | // parseInt stops at first non-digit: '42abc' -> 42
const a1 = strictParse('42abc', 'int');
assert.strictEqual(a1.value, 42);
assert.strictEqual(a1.isValid, true);
// Binary parsing
const a2 = strictParse('1010', 'int', 2);
assert.strictEqual(a2.value, 10);
assert.strictEqual(a2.isValid, true);
// Octal parsing
const... | api_usage |
44 | devbench-api-usage | typescript | import * as assert from 'assert';
// Object transformation utility
// Uses Object.entries() and Object.fromEntries() for key/value transforms
//
// Object.entries({ a: 1, b: 2 }) => [['a', 1], ['b', 2]]
// Object.fromEntries([['a', 1], ['b', 2]]) => { a: 1, b: 2 }
// Demo: filter object to keep only values > threshol... | function mapEntries(
obj: Record<string, number>,
keyFn: (k: string) => string,
valFn: (v: number) => number
): Record<string, number> {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [keyFn(k), valFn(v)])
);
}
| // Transform keys to uppercase, values doubled
const r1 = mapEntries({ x: 1, y: 2 }, k => k.toUpperCase(), v => v * 2);
assert.deepStrictEqual(r1, { X: 2, Y: 4 });
// Prefix keys, negate values
const r2 = mapEntries({ a: 10, b: 20 }, k => 'pre_' + k, v => -v);
assert.deepStrictEqual(r2, { pre_a: -10, pre_b: -20 });
/... | // Key suffix + square values
const a1 = mapEntries({ a: 3, b: 4 }, k => k + '_sq', v => v * v);
assert.deepStrictEqual(a1, { a_sq: 9, b_sq: 16 });
// Single entry
const a2 = mapEntries({ z: 100 }, k => k.repeat(2), v => v / 10);
assert.deepStrictEqual(a2, { zz: 10 });
// Key transform collision (last wins)
const a3 ... | api_usage |
45 | devbench-api-usage | typescript | import * as assert from 'assert';
// AbortController utilities for cancellable operations
// Key API details:
// - controller.abort(reason?) sets signal.aborted=true, signal.reason=reason
// - If no reason provided, signal.reason defaults to a DOMException with name 'AbortError'
// - signal.throwIfAborted() throws sig... | function getAbortInfo(signal: AbortSignal): AbortInfo {
const info: AbortInfo = {
aborted: signal.aborted,
reason: signal.reason,
reasonType: typeof signal.reason,
};
if (signal.reason instanceof Error || (signal.reason && typeof signal.reason === 'object' && 'name' in signal.reason)... | // Not aborted yet
const c1 = new AbortController();
const i1 = getAbortInfo(c1.signal);
assert.strictEqual(i1.aborted, false);
assert.strictEqual(i1.reasonType, 'undefined');
assert.strictEqual(i1.reasonName, undefined);
// Aborted with string reason
const c2 = new AbortController();
c2.abort('timeout');
const i2 = g... | // Aborted with numeric reason
const c4 = new AbortController();
c4.abort(42);
const i4 = getAbortInfo(c4.signal);
assert.strictEqual(i4.aborted, true);
assert.strictEqual(i4.reason, 42);
assert.strictEqual(i4.reasonType, 'number');
assert.strictEqual(i4.reasonName, undefined);
// Aborted with Error object
const c5 = ... | api_usage |
46 | devbench-api-usage | typescript | import * as assert from 'assert';
// Map utility library — operations that preserve insertion order
// Key API: Map preserves insertion order of keys
// Demo: Map from entries preserves order
const demo = new Map<string, number>([['b', 2], ['a', 1], ['c', 3]]);
const keys = [...demo.keys()];
assert.deepStrictEqual(ke... | function invertMap<K, V>(map: Map<K, V>): Map<V, K[]> {
const result = new Map<V, K[]>();
for (const [k, v] of map) {
const existing = result.get(v);
if (existing) {
existing.push(k);
} else {
result.set(v, [k]);
}
}
return result;
}
| // Basic inversion: unique values
const m1 = new Map<string, number>([['a', 1], ['b', 2], ['c', 3]]);
const inv1 = invertMap(m1);
assert.deepStrictEqual(inv1.get(1), ['a']);
assert.deepStrictEqual(inv1.get(2), ['b']);
assert.deepStrictEqual(inv1.get(3), ['c']);
// Duplicate values: keys collected in insertion order
co... | // Empty map
const m3 = new Map<string, string>();
const inv3 = invertMap(m3);
assert.strictEqual(inv3.size, 0);
// All same value
const m4 = new Map<string, number>([['a', 5], ['b', 5], ['c', 5]]);
const inv4 = invertMap(m4);
assert.strictEqual(inv4.size, 1);
assert.deepStrictEqual(inv4.get(5), ['a', 'b', 'c']);
// ... | api_usage |
47 | devbench-api-usage | typescript | import * as assert from 'assert';
// Batch operation result collector using Promise.allSettled
// Key API: Promise.allSettled() never rejects — it returns:
// { status: 'fulfilled', value: T } for resolved promises
// { status: 'rejected', reason: any } for rejected promises
interface BatchResult<T> {
success... | async function batchProcess<T>(fns: (() => Promise<T>)[]): Promise<BatchResult<T>> {
if (fns.length === 0) return { successes: [], failures: [], total: 0, successRate: 0 };
const results = await Promise.allSettled(fns.map(f => f()));
const successes: T[] = [];
const failures: string[] = [];
for (con... | // All succeed
(async () => {
const r1 = await batchProcess([
() => Promise.resolve(1),
() => Promise.resolve(2),
() => Promise.resolve(3),
]);
assert.deepStrictEqual(r1.successes, [1, 2, 3]);
assert.deepStrictEqual(r1.failures, []);
assert.strictEqual(r1.total, 3);
asser... | // Empty input
const r4 = await batchProcess<number>([]);
assert.deepStrictEqual(r4.successes, []);
assert.deepStrictEqual(r4.failures, []);
assert.strictEqual(r4.total, 0);
assert.strictEqual(r4.successRate, 0);
// Single success
const r5 = await batchProcess([() => Promise.resolve(42)... | api_usage |
48 | devbench-api-usage | typescript | import * as assert from 'assert';
// TextEncoder.encodeInto() writes UTF-8 bytes into an existing Uint8Array
// Returns { read: number, written: number }
// read = number of UTF-16 code units consumed from the string
// written = number of UTF-8 bytes written to the buffer
//
// If the buffer is too small, it writ... | function encodeChunk(input: string, maxBytes: number): EncodeChunkResult {
const buf = new Uint8Array(maxBytes);
const { read, written } = encoder.encodeInto(input, buf);
return {
chunk: buf.subarray(0, written),
charsConsumed: read!,
bytesWritten: written!,
complete: read ==... | // ASCII fits perfectly
const r1 = encodeChunk('abc', 10);
assert.strictEqual(r1.charsConsumed, 3);
assert.strictEqual(r1.bytesWritten, 3);
assert.strictEqual(r1.complete, true);
assert.deepStrictEqual([...r1.chunk], [0x61, 0x62, 0x63]);
// Truncation: only 2 bytes available for "Hello"
const r2 = encodeChunk('Hello',... | // Empty string
const a1 = encodeChunk('', 10);
assert.strictEqual(a1.charsConsumed, 0);
assert.strictEqual(a1.bytesWritten, 0);
assert.strictEqual(a1.complete, true);
// Zero-size buffer
const a2 = encodeChunk('test', 0);
assert.strictEqual(a2.charsConsumed, 0);
assert.strictEqual(a2.bytesWritten, 0);
assert.strictEq... | api_usage |
49 | devbench-api-usage | typescript | import * as assert from 'assert';
// Intl.NumberFormat utility for formatting numbers
// Key API details:
// - new Intl.NumberFormat(locale, options).format(number)
// - style: 'decimal' (default), 'currency', 'percent', 'unit'
// - For currency: must provide 'currency' option (ISO 4217 code)
// - For percent: 0.42 fo... | function formatNumber(
value: number, locale: string,
style: 'decimal' | 'currency' | 'percent', currency?: string
): FormatResult {
const options: Intl.NumberFormatOptions = { style };
if (style === 'currency' && currency) options.currency = currency;
return { formatted: new Intl.NumberFormat(local... | // Decimal formatting
const r1 = formatNumber(1234567.89, 'en-US', 'decimal');
assert.strictEqual(r1.formatted, '1,234,567.89');
assert.strictEqual(r1.style, 'decimal');
// Currency formatting
const r2 = formatNumber(42.5, 'en-US', 'currency', 'USD');
assert.strictEqual(r2.formatted, '$42.50');
// Percent formatting ... | // Zero
const a1 = formatNumber(0, 'en-US', 'decimal');
assert.strictEqual(a1.formatted, '0');
// Negative currency
const a2 = formatNumber(-99.99, 'en-US', 'currency', 'USD');
assert.ok(a2.formatted.includes('99.99'));
// Small percent
const a3 = formatNumber(0.005, 'en-US', 'percent');
assert.strictEqual(a3.formatt... | api_usage |
50 | devbench-api-usage | typescript | import * as assert from 'assert';
import * as crypto from 'crypto';
// AES-256-GCM encrypt/decrypt utility
// Key API details for GCM mode:
// - IV must be 12 bytes (96 bits) for GCM — NOT 16 bytes like CBC
// - After cipher.final(), call cipher.getAuthTag() to get 16-byte tag
// - Before decipher.final(), call deciph... | function encryptGCM(plaintext: string, key: Buffer): EncryptedData {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const ct = cipher.update(plaintext, 'utf8', 'hex') + cipher.final('hex');
return { ciphertext: ct, iv: iv.toString('hex'), authTag: cipher... | // Generate a 32-byte key for AES-256
const key = crypto.randomBytes(32);
// Encrypt and verify structure
const enc1 = encryptGCM('Hello, TypeScript!', key);
assert.strictEqual(enc1.algorithm, 'aes-256-gcm');
assert.strictEqual(enc1.iv.length, 24); // 12 bytes = 24 hex chars
assert.strictEqual(enc1.authTag.lengt... | // Empty string encryption
const enc3 = encryptGCM('', key);
assert.strictEqual(enc3.iv.length, 24);
assert.strictEqual(enc3.authTag.length, 32);
const dec3 = decryptGCM(enc3, key);
assert.strictEqual(dec3, '');
// Long string
const longStr = 'A'.repeat(1000);
const enc4 = encryptGCM(longStr, key);
const dec4 = decryp... | api_usage |
1 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface AuditEntry {
from: string;
to: string;
ts: number;
}
class Subscription {
static VALID_TRANSITIONS: Record<string, string[]> = {
pending: ['active'],
active: ['paused', 'cancelled'],
paused: ['active', 'cancelled'],
cancelled:... | activate(ts: number): void {
this._transition('active', ts);
this.activatedAt = ts;
}
|
pause(ts: number): void {
this._transition('paused', ts);
this.pausedAt = ts;
}
}
const s1 = new Subscription('u1', 'pro');
s1.activate(1000);
assert.strictEqual(s1.state, 'active');
assert.strictEqual(s1.activatedAt, 1000);
assert.strictEqual(s1.auditLog.length, 1);
assert.deepStrictEqual(s1.... |
const s2 = new Subscription('u2', 'basic');
s2.activate(500);
assert.strictEqual(s2.state, 'active');
assert.strictEqual(s2.activatedAt, 500);
// Cannot activate again from active state
try {
s2.activate(600);
assert.fail('Should not allow double activation');
} catch (e: any) {
assert.ok(e.message.includ... | code_purpose_understanding |
2 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface PaymentAllocation {
fees: number;
interest: number;
principal: number;
unapplied: number;
}
interface PaymentLogEntry {
paymentId: string;
amount: number;
applied: PaymentAllocation;
}
class LoanAccount {
loanId: string;
feesDue: number;... | applyPayment(paymentId: string, amount: number): PaymentAllocation {
if (this._idempotencyKeys.has(paymentId)) {
return this.auditLog.find(e => e.paymentId === paymentId)!.applied;
}
this._idempotencyKeys.add(paymentId);
let remaining = amount;
const feePart = Mat... | }
const loan = new LoanAccount('L1');
loan.addCharges(50, 200, 1000);
const r1 = loan.applyPayment('P1', 300);
assert.deepStrictEqual(r1, { fees: 50, interest: 200, principal: 50, unapplied: 0 });
assert.strictEqual(loan.feesDue, 0);
assert.strictEqual(loan.interestDue, 0);
assert.strictEqual(loan.principalDue, 950);
|
// Idempotency: same paymentId returns cached result, no side effects
const r1dup = loan.applyPayment('P1', 300);
assert.deepStrictEqual(r1dup, { fees: 50, interest: 200, principal: 50, unapplied: 0 });
assert.strictEqual(loan.principalDue, 950);
// Second payment: all goes to principal
const r2 = loan.applyPayment('... | code_purpose_understanding |
3 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface AdjudicationResult {
memberPay: number;
planPay: number;
}
interface ClaimRecord {
claimId: string;
billed: number;
memberPay: number;
planPay: number;
}
class InsurancePlan {
copay: number;
deductible: number;
coinsurancePct: number;
... | adjudicate(claimId: string, billedAmount: number): AdjudicationResult {
if (this._claimIds.has(claimId)) {
const cached = this.claims.find(c => c.claimId === claimId)!;
return { memberPay: cached.memberPay, planPay: cached.planPay };
}
this._claimIds.add(claimId);
... | }
const plan = new InsurancePlan(30, 500, 0.2, 2000);
const c1 = plan.adjudicate('C1', 1000);
assert.strictEqual(c1.memberPay, 624);
assert.strictEqual(c1.planPay, 376);
assert.strictEqual(plan.deductibleMet, 500);
assert.strictEqual(plan.oopAccumulator, 624);
|
// Claim 2: $2000 billed, deductible already met
const c2 = plan.adjudicate('C2', 2000);
assert.strictEqual(c2.memberPay, 424);
assert.strictEqual(c2.planPay, 1576);
assert.strictEqual(plan.oopAccumulator, 1048);
// Claim 3: $8000 billed - OOP cap kicks in
const c3 = plan.adjudicate('C3', 8000);
assert.strictEqual(c3... | code_purpose_understanding |
4 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface ReleaseResult {
released: number;
blocked: boolean;
reason?: string;
}
interface ReleaseLogEntry {
milestoneId: string;
gross: number;
holdback: number;
net: number;
}
class EscrowAccount {
totalAmount: number;
holdbackPct: number;
r... | releaseMilestone(milestoneId: string): ReleaseResult {
if (this._processedIds.has(milestoneId)) {
const cached = this.log.find(e => e.milestoneId === milestoneId)!;
return { released: cached.net, blocked: false };
}
if (!this.milestones[milestoneId]) {
ret... | }
const escrow = new EscrowAccount(100000, 0.1);
escrow.registerMilestone('M1', 0.3);
escrow.registerMilestone('M2', 0.5);
escrow.registerMilestone('M3', 0.2);
const r1 = escrow.releaseMilestone('M1');
assert.strictEqual(r1.released, 27000);
assert.strictEqual(r1.blocked, false);
assert.strictEqual(escrow.released, 2... |
// Defect blocks release
escrow.reportDefect('D1');
const r2 = escrow.releaseMilestone('M2');
assert.strictEqual(r2.blocked, true);
assert.strictEqual(r2.reason, 'defects_pending');
assert.strictEqual(escrow.released, 27000);
// Resolve defect, now M2 releases
escrow.resolveDefect('D1');
const r2b = escrow.releaseMil... | code_purpose_understanding |
5 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface CreditEntry {
id: string;
amount: number;
}
interface CreditUsed {
id: string;
used: number;
}
interface Invoice {
gross: number;
net: number;
creditsUsed: CreditUsed[];
}
class UsageBilling {
ratePerUnit: number;
minimumCommit: number;... | closePeriod(periodId: string, units: number): Invoice {
if (this.invoices[periodId]) {
return this.invoices[periodId];
}
const gross = Math.max(units * this.ratePerUnit, this.minimumCommit);
let remaining = gross;
const creditsUsed: CreditUsed[] = [];
whil... | }
const billing = new UsageBilling(0.05, 100);
billing.addCredit('CR1', 30);
billing.addCredit('CR2', 50);
const inv1 = billing.closePeriod('JAN', 3000);
assert.strictEqual(inv1.gross, 150);
assert.strictEqual(inv1.net, 70);
assert.deepStrictEqual(inv1.creditsUsed, [{ id: 'CR1', used: 30 }, { id: 'CR2', used: 50 }]);... |
// Period 2: low usage, minimum commit kicks in
const inv2 = billing.closePeriod('FEB', 500);
assert.strictEqual(inv2.gross, 100);
assert.strictEqual(inv2.net, 100);
assert.strictEqual(billing.totalBilled, 170);
// Add credit, test partial consumption
billing.addCredit('CR3', 200);
const inv3 = billing.closePeriod('M... | code_purpose_understanding |
6 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface Batch {
batchId: string;
qty: number;
expiresAt: number;
}
interface AllocationEntry {
batchId: string;
qty: number;
}
interface AllocationResult {
success: boolean;
allocations: AllocationEntry[];
reason?: string;
}
class Warehouse {
b... | reserve(orderId: string, requestedQty: number, now: number): AllocationResult {
if (this.reservations[orderId]) {
return { success: true, allocations: this.reservations[orderId] };
}
const validBatches = this.batches.filter(b => b.expiresAt > now && b.qty > 0);
let remain... | }
const wh = new Warehouse();
wh.receiveBatch('B1', 10, 1000);
wh.receiveBatch('B2', 20, 2000);
wh.receiveBatch('B3', 5, 500);
// FEFO: B3 expires first (500), then B1 (1000), then B2 (2000)
// At now=400, all valid. Request 12: B3(5) + B1(7) = 12
const r1 = wh.reserve('O1', 12, 400);
assert.strictEqual(r1.success, t... |
// B3 is now 0, B1 is now 3, B2 is still 20
// At now=600, B3 is expired anyway. Request 25: B1(3) + B2(20) = 23 < 25
const r2 = wh.reserve('O2', 25, 600);
assert.strictEqual(r2.success, false);
assert.strictEqual(r2.reason, 'insufficient_stock');
// Stock unchanged after failed reservation
assert.strictEqual(wh.batch... | code_purpose_understanding |
7 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface LineItem {
sku: string;
qty: number;
unitPrice: number;
}
interface OrderResult {
subtotal: number;
discount: number;
taxableAmount: number;
tax: number;
shipping: number;
total: number;
error?: string;
}
class OrderProcessor {
t... | processOrder(orderId: string, items: LineItem[]): OrderResult {
if (this._processedOrders.has(orderId)) {
return this._processedOrders.get(orderId)!;
}
const subtotal = items.reduce((sum, item) => sum + item.qty * item.unitPrice, 0);
if (subtotal < this.minimumOrder) {
... | }
const proc = new OrderProcessor({
taxRate: 0.08,
freeShippingThreshold: 100,
shippingCost: 12,
minimumOrder: 25,
discountTiers: [{ min: 200, pct: 0.15 }, { min: 100, pct: 0.10 }, { min: 50, pct: 0.05 }]
});
const o1 = proc.processOrder('ORD1', [{ sku: 'A', qty: 2, unitPrice: 60 }]);
assert.stric... |
// Below minimum order
const o2 = proc.processOrder('ORD2', [{ sku: 'B', qty: 1, unitPrice: 20 }]);
assert.strictEqual(o2.error, 'below_minimum');
assert.strictEqual(o2.total, 0);
// High tier discount + free shipping
const o3 = proc.processOrder('ORD3', [{ sku: 'C', qty: 5, unitPrice: 50 }]);
assert.strictEqual(o3.s... | code_purpose_understanding |
8 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface TaxBracket {
upTo: number;
rate: number;
}
interface PayStub {
gross: number;
preTaxDeductions: number;
taxableIncome: number;
tax: number;
postTaxDeductions: number;
net: number;
}
class PayrollProcessor {
brackets: TaxBracket[];
pr... | runPayroll(periodId: string, gross: number): PayStub {
if (this._processedPeriods.has(periodId)) {
return this._processedPeriods.get(periodId)!;
}
const preTaxDeductions = Math.round(gross * this.preTaxPct * 100) / 100;
const taxableIncome = gross - preTaxDeductions;
... | }
const payroll = new PayrollProcessor(
[{ upTo: 1000, rate: 0.10 }, { upTo: 3000, rate: 0.20 }, { upTo: Infinity, rate: 0.30 }],
0.05,
50
);
// Gross 4000: preTax=200, taxable=3800, tax=100+400+240=740, postTax=50, net=3010
const s1 = payroll.runPayroll('JAN', 4000);
assert.strictEqual(s1.gross, 4000);
a... |
// Low income: only first bracket
const s2 = payroll.runPayroll('FEB', 800);
assert.strictEqual(s2.preTaxDeductions, 40);
assert.strictEqual(s2.taxableIncome, 760);
assert.strictEqual(s2.tax, 76);
assert.strictEqual(s2.net, 634);
// YTD tracking
assert.strictEqual(payroll.ytdGross, 4800);
assert.strictEqual(payroll.y... | code_purpose_understanding |
9 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface ReplenishmentOrder {
orderId: string;
sku: string;
qty: number;
reason: string;
}
interface CheckResult {
needsOrder: boolean;
order?: ReplenishmentOrder;
}
class InventoryPlanner {
sku: string;
onHand: number;
dailyDemand: number;
l... | checkReplenishment(periodId: string): CheckResult {
if (this._cachedResults.has(periodId)) {
return this._cachedResults.get(periodId)!;
}
const safetyStock = this.dailyDemand * this.safetyStockDays;
const reorderPoint = this.dailyDemand * this.leadTimeDays + safetyStock;
... | }
const planner = new InventoryPlanner({
sku: 'WIDGET-A',
onHand: 100,
dailyDemand: 10,
leadTimeDays: 7,
safetyStockDays: 3,
orderingCost: 50,
holdingCostPerUnit: 2
});
// reorderPoint = 10*7 + 10*3 = 100. projectedStock = 100 <= 100 → needs order
// EOQ = sqrt(2 * 10 * 365 * 50 / 2) = sqr... |
// Now projectedStock = 100 + 427 = 527 > 100, no order needed
const c2 = planner.checkReplenishment('DAY2');
assert.strictEqual(c2.needsOrder, false);
// Consume stock to make it critical
planner.consumeStock(80);
// onHand=20, pendingQty=427, projected=447 > 100 → still ok
const c3 = planner.checkReplenishment('DAY... | code_purpose_understanding |
10 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface CommissionResult {
baseCommission: number;
teamBonus: number;
clawback: number;
net: number;
cappedAt: number | null;
}
interface SaleRecord {
dealId: string;
amount: number;
refunded: boolean;
}
class CommissionEngine {
tiers: { upTo: n... | recordSale(dealId: string, amount: number): CommissionResult {
if (this._processedDeals.has(dealId)) {
return this._processedDeals.get(dealId)!;
}
this.sales.push({ dealId, amount, refunded: false });
let baseCommission = 0;
let prev = 0;
for (const tier o... | }
const engine = new CommissionEngine({
tiers: [{ upTo: 10000, rate: 0.05 }, { upTo: 50000, rate: 0.08 }, { upTo: Infinity, rate: 0.12 }],
teamBonusPct: 0.10,
teamQuota: 100000,
annualCap: 25000
});
// Deal 1: $30000 → base = 500 + 1600 = 2100, sales=30000 < 100000 → no bonus
const d1 = engine.recordS... |
// Deal 2: $80000 → base = 500 + 3200 + 3600 = 7300, totalSales=110000 >= 100000 → bonus=730
const d2 = engine.recordSale('D2', 80000);
assert.strictEqual(d2.baseCommission, 7300);
assert.strictEqual(d2.teamBonus, 730);
assert.strictEqual(d2.net, 8030);
// YTD = 2100 + 8030 = 10130
assert.strictEqual(engine.ytdCommis... | code_purpose_understanding |
11 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface Booking {
bookingId: string;
room: string;
start: number;
end: number;
priority: number;
expiresAt: number;
preemptedBy: string | null;
}
class RoomBookingSystem {
private bookings: Map<string, Booking> = new Map();
private roomS... | book(bookingId: string, room: string, start: number, end: number,
priority: number, expiresAt: number, currentTime: number):
{ success: boolean; preempted?: string[]; reason?: string } {
if (this.bookings.has(bookingId)) {
const existing = this.bookings.get(bookingId)!;
... | }
const sys = new RoomBookingSystem();
// Basic booking
const r1 = sys.book('B1', 'Room-A', 100, 200, 5, 9999, 0);
assert.equal(r1.success, true);
assert.deepEqual(r1.preempted, []);
// Overlap with lower priority — rejected
const r2 = sys.book('B2', 'Room-A', 150, 250, 3, 9999, 0);
assert.equal(r2.success, false);
... |
// Equal priority — also rejected (STRICTLY greater required)
const r2b = sys.book('B2b', 'Room-A', 150, 250, 5, 9999, 0);
assert.equal(r2b.success, false);
assert.equal(r2b.reason, 'lower_or_equal_priority');
// Higher priority — preempts B1
const r3 = sys.book('B3', 'Room-A', 150, 250, 8, 9999, 0);
assert.equal(r3.... | code_purpose_understanding |
12 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface Allocation {
jobId: string;
cpus: number;
memMB: number;
priority: number;
allocatedAt: number;
deallocatedAt: number | null;
}
class ResourceAllocator {
private totalCpus: number;
private totalMemMB: number;
private cooldownMs: ... | allocate(jobId: string, cpus: number, memMB: number, priority: number, currentTime: number):
{ success: boolean; preempted?: string[]; reason?: string } {
const existing = this.allocations.get(jobId);
if (existing && existing.deallocatedAt === null) {
return { success: true,... | }
const ra = new ResourceAllocator(8, 1024, 5000);
// Allocate job1: 4 CPUs, 512MB, priority 5
const a1 = ra.allocate('job1', 4, 512, 5, 1000);
assert.equal(a1.success, true);
assert.deepEqual(a1.preempted, []);
// Allocate job2: 4 CPUs, 512MB, priority 3
const a2 = ra.allocate('job2', 4, 512, 3, 2000);
assert.equal... |
// job3 with higher priority preempts job2 (lowest)
const a3b = ra.allocate('job3', 2, 256, 4, 3000);
assert.equal(a3b.success, true);
assert.deepEqual(a3b.preempted, ['job2']);
// Idempotent: re-allocate job1 returns cached
const a1dup = ra.allocate('job1', 4, 512, 5, 3500);
assert.equal(a1dup.success, true);
assert... | code_purpose_understanding |
13 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface ClaimResult {
memberPay: number;
planPay: number;
denied: boolean;
reason?: string;
}
class ClaimAdjudicator {
private copay: number;
private deductible: number;
private coinsurancePct: number;
private oopMax: number;
private pri... | adjudicate(claimId: string, serviceCode: string, billedAmount: number, claimDay: number): ClaimResult {
if (this.claimCache.has(claimId)) {
return this.claimCache.get(claimId)!;
}
if (claimDay < this.enrollmentDay + this.waitingPeriodDays) {
const r: ClaimResult = { m... | }
// Plan: $30 copay, $500 deductible, 20% coinsurance, $2000 OOP max,
// prior auth required for claims >= $5000, 30-day waiting period, enrolled day 0
const adj = new ClaimAdjudicator(30, 500, 0.2, 2000, 5000, 30, 0);
// Claim during waiting period — denied
const c0 = adj.adjudicate('C0', 'XRAY', 200, 10);
assert.e... |
// $5000 claim without prior auth — denied
const c2 = adj.adjudicate('C2', 'MRI', 5000, 40);
assert.equal(c2.denied, true);
assert.equal(c2.reason, 'no_prior_auth');
// Add prior auth, retry with different claimId
adj.addPriorAuth('MRI');
// oopAccumulator=624, deductible fully met
// copay=30, deductible=0, coinsura... | code_purpose_understanding |
14 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface TaxBracket {
upTo: number; // upper bound of bracket (Infinity for last)
rate: number; // marginal rate (0.0-1.0)
}
interface TaxResult {
grossTax: number;
credits: number;
netTax: number;
withheld: number;
refundOrOwed: number; // ... | calculate(filingId: string, grossIncome: number, credits: number, withheld: number): TaxResult {
if (this.results.has(filingId)) {
return this.results.get(filingId)!;
}
const taxableIncome = Math.max(0, grossIncome - this.standardDeduction);
let grossTax = 0;
let ... | }
const calc = new TaxCalculator(
[
{ upTo: 10000, rate: 0.10 },
{ upTo: 40000, rate: 0.20 },
{ upTo: 100000, rate: 0.30 },
{ upTo: Infinity, rate: 0.40 }
],
15000 // standard deduction
);
// $60000 income: taxable = 60000 - 15000 = 45000
// Bracket 1: 10000 * 0.10 = 1000
... |
// Low income: taxable < 0 -> 0
// $10000 income: taxable = max(0, 10000-15000) = 0
// grossTax=0, credits=500 but applied=min(500,0)=0, netTax=0, withheld=800 -> refund=800
const r2 = calc.calculate('F2', 10000, 500, 800);
assert.equal(r2.grossTax, 0);
assert.equal(r2.credits, 0);
assert.equal(r2.netTax, 0);
assert.e... | code_purpose_understanding |
15 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface ExpenseResult {
approved: boolean;
reason?: string;
remaining: number;
approvalLevel: string;
}
class BudgetTracker {
private quarterlyBudget: number;
private rolloverCapPct: number;
private spent: number = 0;
private rollover: numbe... | submitExpense(expenseId: string, amount: number): ExpenseResult {
if (this.expenseLog.has(expenseId)) {
return this.expenseLog.get(expenseId)!;
}
if (this.frozen) {
const r: ExpenseResult = { approved: false, reason: 'budget_frozen', remaining: this.available(), appro... | }
const bt = new BudgetTracker(50000, 0.1); // $50k quarterly, 10% rollover cap
const e1 = bt.submitExpense('E1', 500);
assert.equal(e1.approved, true);
assert.equal(e1.approvalLevel, 'auto');
assert.equal(e1.remaining, 49500);
const e2 = bt.submitExpense('E2', 3000);
assert.equal(e2.approved, true);
assert.equal(e... |
// Director approval
const e3 = bt.submitExpense('E3', 10000);
assert.equal(e3.approved, true);
assert.equal(e3.approvalLevel, 'director');
assert.equal(e3.remaining, 36500);
// VP approval
const e4 = bt.submitExpense('E4', 25000);
assert.equal(e4.approved, true);
assert.equal(e4.approvalLevel, 'vp');
assert.equal(e4... | code_purpose_understanding |
16 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
type ApprovalStatus = 'pending' | 'approved' | 'rejected' | 'timed_out';
interface StageResult {
stage: number;
status: ApprovalStatus;
approver: string;
timestamp: number;
}
interface RequestState {
requestId: string;
currentStage: number;
total... | processStage(requestId: string, stage: number, approver: string,
decision: 'approved' | 'rejected', timestamp: number):
{ processed: boolean; requestStatus: string; reason?: string } {
const key = requestId + ':' + stage;
if (this.stageAttempts.has(key)) {
... | }
const chain = new ApprovalChain();
chain.createRequest('REQ1', 3, 10000); // 3 stages, 10s timeout per stage
// Stage 0: Alice approves
const s0 = chain.processStage('REQ1', 0, 'Alice', 'approved', 1000);
assert.equal(s0.processed, true);
assert.equal(s0.requestStatus, 'in_progress');
// Stage 1: Bob approves
con... |
// Idempotent: reprocess stage 0 returns duplicate
const s0dup = chain.processStage('REQ1', 0, 'Alice', 'approved', 1000);
assert.equal(s0dup.processed, false);
assert.equal(s0dup.reason, 'duplicate');
// REQ2: test same-approver rejection
chain.createRequest('REQ2', 3, 10000);
chain.processStage('REQ2', 0, 'Dave', '... | code_purpose_understanding |
17 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
type TaskStatus = 'pending' | 'ready' | 'running' | 'completed' | 'failed' | 'blocked';
interface ScheduledTask {
taskId: string;
deps: string[];
status: TaskStatus;
retries: number;
maxRetries: number;
nextRetryAt: number;
baseDelayMs: number;
}
... | submit(taskId: string, deps: string[], maxRetries: number, baseDelayMs: number):
{ accepted: boolean; status: TaskStatus; reason?: string } {
if (this.tasks.has(taskId)) {
return { accepted: true, status: this.tasks.get(taskId)!.status };
}
if (this.hasCircular(taskId,... |
// complete(taskId): marks as completed, updates dependents
complete(taskId: string): void {
const task = this.tasks.get(taskId);
if (!task) return;
task.status = 'completed';
for (const [, t] of this.tasks) {
if (t.deps.includes(taskId) && t.status === 'pending') {
... |
// Fail B with retries: exponential backoff
const f1 = sched.fail('B', 10000);
assert.equal(f1.retrying, true);
assert.equal(f1.nextRetryAt, 12000); // 10000 + 2000*2^0 = 12000
const f2 = sched.fail('B', 13000);
assert.equal(f2.retrying, true);
assert.equal(f2.nextRetryAt, 17000); // 13000 + 2000*2^1 = 17000
const... | code_purpose_understanding |
18 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface FieldSchema {
name: string;
type: 'string' | 'number' | 'boolean';
required: boolean;
}
interface ETLRecord {
[key: string]: any;
}
interface ETLResult {
accepted: ETLRecord[];
quarantined: { record: ETLRecord; reason: string }[];
dupli... | processBatch(records: ETLRecord[]): ETLResult {
const accepted: ETLRecord[] = [];
const quarantined: { record: ETLRecord; reason: string }[] = [];
let duplicatesSkipped = 0;
const batchKeys: string[] = [];
for (const raw of records) {
const record = { ...raw };
... | }
const pipeline = new ETLPipeline(
[
{ name: 'id', type: 'string', required: true },
{ name: 'amount', type: 'number', required: true },
{ name: 'active', type: 'boolean', required: false }
],
['id'],
0.5 // rollback if >50% quarantined
);
pipeline.addTransform(r => ({ ...r, ... |
// Dedup: A already seen from batch1
const batch2 = pipeline.processBatch([
{ id: 'A', amount: '99' },
{ id: 'D', amount: '30' }
]);
assert.equal(batch2.duplicatesSkipped, 1);
assert.equal(batch2.accepted.length, 1);
assert.equal(batch2.accepted[0].id, 'D');
// Rollback: >50% quarantined -> no records accepte... | code_purpose_understanding |
19 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface CacheEntry<T> {
key: string;
value: T;
insertedAt: number;
lastAccessedAt: number;
ttlMs: number;
staleMs: number;
refreshing: boolean;
}
interface CacheGetResult<T> {
value: T | null;
status: 'hit' | 'miss' | 'stale' | 'expired'... | put(key: string, value: T, ttlMs: number, staleMs: number, currentTime: number): void {
if (this.entries.has(key)) {
this.entries.delete(key);
} else if (this.entries.size >= this.capacity) {
let lruKey = '';
let lruTime = Infinity;
for (const [k, e] o... | }
const cache = new CacheManager<string>(3);
cache.put('a', 'val-a', 1000, 500, 0); // TTL=1s, stale=0.5s
cache.put('b', 'val-b', 2000, 1000, 0); // TTL=2s, stale=1s
cache.put('c', 'val-c', 1000, 500, 0);
// Fresh hit
const g1 = cache.get('a', 500);
assert.equal(g1.status, 'hit');
assert.equal(g1.value, 'val-a');... |
// Expired (past TTL + stale window): 1000+500=1500, time=1600
const g3 = cache.get('a', 1600);
assert.equal(g3.status, 'expired');
assert.equal(g3.value, null);
// b is still fresh at 1500
const g4 = cache.get('b', 1500);
assert.equal(g4.status, 'hit');
assert.equal(g4.value, 'val-b');
// LRU eviction: capacity=3, ... | code_purpose_understanding |
20 | devbench-code-purpose-understanding | typescript | import { strict as assert } from 'assert';
interface RateLimitResult {
allowed: boolean;
tokensRemaining: number;
quotaRemaining: number;
reason?: string;
retryAfterMs?: number;
}
class RateLimiter {
private maxTokens: number;
private refillRatePerMs: number;
private dailyQuota: number... | request(requestId: string, cost: number, currentTime: number): RateLimitResult {
if (this.requestLog.has(requestId)) {
return this.requestLog.get(requestId)!;
}
// Refill tokens
const elapsed = currentTime - this.lastRefillAt;
this.tokens = Math.min(this.maxTokens... | }
// maxTokens=10, refill=0.01/ms (10/s), dailyQuota=100, penalty after 3 rejects, 5s penalty
const rl = new RateLimiter(10, 0.01, 100, 3, 5000, 0);
// Request costs 3 tokens at t=100
// tokens=10, elapsed=100, refill=100*0.01=1, tokens=min(10,11)=10, then 10-3=7
const r1 = rl.request('R1', 3, 100);
assert.equal(r1.a... |
assert.equal(r1.quotaRemaining, 99);
// R2: cost=5 at t=200, elapsed=100, refill=1, tokens=min(10,7+1)=8, 8-5=3
const r2 = rl.request('R2', 5, 200);
assert.equal(r2.allowed, true);
assert.equal(r2.tokensRemaining, 3);
// R3: cost=5 at t=250, elapsed=50, refill=0.5, tokens=min(10,3+0.5)=3.5, 5>3.5 -> rejected
const r... | code_purpose_understanding |
21 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface CartItem {
sku: string;
price: number;
qty: number;
taxable: boolean;
}
interface CartResult {
subtotal: number;
discount: number;
taxAmount: number;
shippingFee: number;
total: number;
freeShippingApplied: boolean;
}
class ShoppingC... | checkout(): CartResult {
const round2 = (v: number) => Math.round(v * 100) / 100;
const subtotal = round2(this.items.reduce((s, i) => s + i.price * i.qty, 0));
let discount = 0;
for (const tier of this.discountTiers) {
if (subtotal >= tier.minSubtotal) {
d... |
}
// Tiers: 15% off over $200, 10% off over $100, 5% off over $50
const cart = new ShoppingCart(0.08, 150, 12.99,
[{ minSubtotal: 200, rate: 0.15 }, { minSubtotal: 100, rate: 0.10 }, { minSubtotal: 50, rate: 0.05 }]);
cart.addItem('SHIRT', 39.99, 3, true); // 119.97, taxable
cart.addItem('BOOK', 15.00, 2, fals... |
// Add more items to push past free shipping threshold
cart.addItem('SHIRT', 39.99, 2, true); // now 5 shirts = 199.95
// subtotal = 199.95 + 30 = 229.95
// Best tier: 200 => 15% => discount = round(229.95*0.15*100)/100 = 34.49
// discountedSubtotal = 195.46
// tax on taxable: round(199.95 * 0.08 * 100) / 100 = 16.00... | code_purpose_understanding |
22 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface GiftCard {
cardId: string;
balance: number;
expiryDate: number; // epoch day
redeemed: boolean;
}
interface RedemptionResult {
success: boolean;
amountCharged: number;
remainingOrderBalance: number;
cardBalances: Record<string, number>;
... | redeemForOrder(orderId: string, cardIds: string[], orderTotal: number, currentDate: number): RedemptionResult {
if (this.processedOrders.has(orderId)) {
return { success: false, amountCharged: 0, remainingOrderBalance: orderTotal,
cardBalances: {}, expired: [], reason: 'dupl... |
}
const gcs = new GiftCardSystem();
gcs.registerCard('GC1', 25.00, 100); // $25, expires day 100
gcs.registerCard('GC2', 50.00, 200); // $50, expires day 200
gcs.registerCard('GC3', 10.00, 50); // $10, expires day 50 (will be expired)
// Order $60 on day 75, using GC3 (expired), GC1, GC2
// GC3 expired (50 < ... |
// Idempotent: same orderId
const r2 = gcs.redeemForOrder('ORD1', ['GC2'], 10, 76);
assert.strictEqual(r2.success, false);
assert.strictEqual(r2.reason, 'duplicate_order');
// Partial: not enough balance
const r3 = gcs.redeemForOrder('ORD2', ['GC2'], 30, 76);
// GC2 has 15 left. Take 15, remaining=15.
assert.strictEq... | code_purpose_understanding |
23 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface Payment {
method: string; // 'credit' | 'giftcard' | 'loyalty'
amount: number;
}
interface OrderRecord {
orderId: string;
items: { sku: string; price: number; qty: number }[];
payments: Payment[];
refunded: Map<string, number>; // sku -> qty alre... | processRefund(orderId: string, sku: string, qty: number,
refundDate: number, orderDate: number): RefundResult {
const order = this.orders.get(orderId);
if (!order) {
return { success: false, reason: 'unknown_order', restockingFee: 0, refundAmount: 0, refundSplit: [] };... |
}
const rp = new RefundProcessor(0.15, 30); // 15% restocking fee, waived within 30 days
rp.addOrder('O1',
[{ sku: 'LAPTOP', price: 999.99, qty: 1 }, { sku: 'MOUSE', price: 29.99, qty: 3 }],
[{ method: 'credit', amount: 800 }, { method: 'giftcard', amount: 200 }, { method: 'loyalty', amount: 89.96 }],
1... |
// Refund LAPTOP after waiver (day 200, diff=100 > 30): restocking fee applies
const r2 = rp.processRefund('O1', 'LAPTOP', 1, 200, 100);
assert.strictEqual(r2.success, true);
assert.strictEqual(r2.restockingFee, 150.00); // round(999.99*0.15*100)/100 = 150.00
assert.strictEqual(r2.refundAmount, 849.99); // 999.9... | code_purpose_understanding |
24 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface LeaveBalance {
annual: number;
sick: number;
carryover: number; // annual leave carried from last year
}
interface LeaveRequest {
reqId: string;
empId: string;
type: 'annual' | 'sick';
days: number;
status: 'pending' | 'approved' | 'denied';... | requestLeave(reqId: string, empId: string, type: 'annual' | 'sick',
days: number, hasDocumentation: boolean = false): LeaveResult {
if (this.requests.has(reqId)) {
const existing = this.requests.get(reqId)!;
return { approved: existing.status === 'approved', reason:... |
}
const lm = new LeaveManager(5, 3); // max 5 carryover days, sick > 3 days needs docs
lm.addEmployee('E1', 15, 10, 8); // 8 carryover capped to 5
const bal = lm.balances.get('E1')!;
assert.strictEqual(bal.carryover, 5); // capped
// Annual leave: 7 days. Deduct carryover first (5), then annual (2).
const r1 = l... |
// Sick leave 5 days without doc: denied (5 > 3)
const r3 = lm.requestLeave('R3', 'E1', 'sick', 5, false);
assert.strictEqual(r3.approved, false);
assert.strictEqual(r3.reason, 'documentation_required');
// Sick leave 5 days with doc: approved
const r4 = lm.requestLeave('R4', 'E1', 'sick', 5, true);
assert.strictEqua... | code_purpose_understanding |
25 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface TimesheetEntry {
day: string; // 'mon' | 'tue' | ... | 'sun'
hours: number;
}
interface PayResult {
regularHours: number;
overtimeHours: number;
weekendHours: number;
regularPay: number;
overtimePay: number;
weekendPay: number;
tota... | calculatePay(entries: TimesheetEntry[]): PayResult {
let weekendHours = 0;
let weekdayHours = 0;
for (const e of entries) {
if (this.weekendDays.has(e.day)) {
weekendHours += e.hours;
} else {
weekdayHours += e.hours;
}
... |
}
// $25/hr, 40hr cap, 1.5x OT, 2x weekend, $2000 weekly cap
const tp = new TimesheetProcessor(25, 40, 1.5, 2.0, 2000);
const r1 = tp.calculatePay([
{ day: 'mon', hours: 9 }, { day: 'tue', hours: 9 },
{ day: 'wed', hours: 9 }, { day: 'thu', hours: 9 },
{ day: 'fri', hours: 8 }, // weekday total: 44
{... |
// Trigger cap
const r2 = tp.calculatePay([
{ day: 'mon', hours: 10 }, { day: 'tue', hours: 10 },
{ day: 'wed', hours: 10 }, { day: 'thu', hours: 10 },
{ day: 'fri', hours: 10 }, // weekday total: 50
{ day: 'sat', hours: 8 }, { day: 'sun', hours: 8 }, // weekend: 16
]);
// regular=40, OT=10, weekend=1... | code_purpose_understanding |
26 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface Employee {
empId: string;
baseSalary: number;
hireDate: number; // epoch day
performanceScore: number; // 0.0 - 5.0
department: string;
terminated: boolean;
}
interface BonusResult {
eligible: boolean;
reason?: string;
baseBonus... | calculateBonus(empId: string, evaluationDate: number, fiscalYearStart: number): BonusResult {
const emp = this.employees.get(empId);
if (!emp || emp.terminated) {
return { eligible: false, reason: emp ? 'terminated' : 'unknown_employee',
baseBonus: 0, tenureMultiplie... |
}
const bc = new BonusCalculator(
[{ threshold: 4.5, bonusRate: 0.20 }, { threshold: 3.5, bonusRate: 0.10 }, { threshold: 2.5, bonusRate: 0.05 }],
[{ years: 10, multiplier: 1.5 }, { years: 5, multiplier: 1.25 }, { years: 2, multiplier: 1.1 }],
2.0 // min score
);
bc.addEmployee('E1', 100000, 0, 4.8, 'En... |
// New hire mid-fiscal-year: proration applies
bc.addEmployee('E3', 120000, 500, 4.0, 'Sales'); // hired day 500, FY started 365
// score 4.0 >= 3.5 => 10%. base=12000. tenure: floor(230/365)=0 => 1.0.
// Hired 500 > FY 365 => proration=(730-500)/(730-365)=230/365=0.6301...
// final=12000*1.0*0.6301...=7561.64
const ... | code_purpose_understanding |
27 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface Appointment {
apptId: string;
patientId: string;
start: number; // minutes from midnight
end: number;
priority: number; // higher = more urgent
status: 'scheduled' | 'bumped';
}
interface ScheduleResult {
success: boolean;
reason?: strin... | schedule(apptId: string, patientId: string, start: number,
duration: number, priority: number): ScheduleResult {
if (this.idSet.has(apptId)) {
return { success: false, reason: 'duplicate' };
}
const end = start + duration;
const conflicts = this.appointments.... |
}
const clinic = new ClinicScheduler(15); // 15-minute buffer between appointments
// Schedule A1: 9:00-9:30 (540-570), priority 1
const s1 = clinic.schedule('A1', 'P1', 540, 30, 1);
assert.strictEqual(s1.success, true);
assert.deepStrictEqual(s1.bumped, []);
// Schedule A2: 10:00-10:30 (600-630), priority 1 — no ... |
// Can't bump A3 (priority 3) with equal priority
const s4 = clinic.schedule('A4', 'P4', 570, 20, 3);
assert.strictEqual(s4.success, false);
assert.strictEqual(s4.reason, 'priority_conflict');
// Can bump A3 with higher priority
const s5 = clinic.schedule('A5', 'P5', 560, 30, 5);
assert.strictEqual(s5.success, true);... | code_purpose_understanding |
28 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface DrugInfo {
name: string;
maxDailyDoseMg: number;
minIntervalHours: number; // minimum hours between doses
interactsWith: string[]; // drug names that conflict
}
interface ActivePrescription {
drug: string;
doseMg: number;
lastAdministered: num... | administerDose(drug: string, doseMg: number, currentHour: number): AdminResult {
const info = this.drugDb.get(drug);
if (!info) {
return { allowed: false, reason: 'unknown_drug', warnings: [] };
}
// Check interactions
for (const conflict of info.interactsWith) {
... |
}
const pv = new PrescriptionValidator();
pv.registerDrug('ibuprofen', 1200, 6, ['aspirin']);
pv.registerDrug('aspirin', 4000, 4, ['ibuprofen']);
pv.registerDrug('acetaminophen', 3000, 4, []);
// First dose of ibuprofen: 400mg at hour 0
const d1 = pv.administerDose('ibuprofen', 400, 0);
assert.strictEqual(d1.allowed... |
// After 6 hours: allowed, approaching limit warning
const d4 = pv.administerDose('ibuprofen', 400, 6);
assert.strictEqual(d4.allowed, true);
assert.strictEqual(d4.totalTodayMg, 800);
assert.deepStrictEqual(d4.warnings, []);
// Third dose at hour 12: 400+400+400=1200 = 100% of limit
const d5 = pv.administerDose('ibup... | code_purpose_understanding |
29 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface Package {
pkgId: string;
weight: number; // kg
destination: string; // zone code
}
interface ShipmentResult {
shipmentId: string;
packages: string[];
totalWeight: number;
zone: string;
baseCost: number;
weightSurcharge: number;
c... | createShipment(shipmentId: string, packages: Package[]): ShipmentResult | { error: string; pkgId?: string } {
// Check for duplicate packages
for (const pkg of packages) {
if (this.processedPkgs.has(pkg.pkgId)) {
return { error: 'duplicate_package', pkgId: pkg.pkgId };
... |
}
const dr = new DeliveryRouter(
{ 'ZONE_A': 10, 'ZONE_B': 25, 'ZONE_C': 50 },
[{ minKg: 30, ratePerKg: 3.0 }, { minKg: 10, ratePerKg: 1.5 }, { minKg: 5, ratePerKg: 0.5 }],
2.0 // $2 discount per extra package
);
// Single package to ZONE_A, 8kg
// baseCost=10, weight 8 >= 5 => surcharge = (8-5)*0.5 = 1... |
// Mixed zones
const s3 = dr.createShipment('S3', [
{ pkgId: 'P5', weight: 5, destination: 'ZONE_A' },
{ pkgId: 'P6', weight: 5, destination: 'ZONE_B' },
]);
assert.strictEqual((s3 as any).error, 'mixed_zones');
// Duplicate package
const s4 = dr.createShipment('S4', [{ pkgId: 'P1', weight: 5, destination: 'Z... | code_purpose_understanding |
30 | devbench-code-purpose-understanding | typescript | import * as assert from 'assert';
interface BinStock {
binId: string;
sku: string;
qty: number;
unitWeight: number; // kg per unit
pickPriority: number; // lower = pick first
}
interface OrderLine {
sku: string;
qtyRequested: number;
}
interface PickInstruction {
binId: string;
... | pickOrder(orderId: string, lines: OrderLine[]): PickResult | { error: string } {
if (this.processedOrders.has(orderId)) {
return { error: 'duplicate_order' };
}
const picks: PickInstruction[] = [];
let totalWeight = 0;
const unfulfilled: { sku: string; qtyShort: n... |
}
const wp = new WarehousePicker(50); // 50kg max container
wp.addBin('BIN-A', 'WIDGET', 20, 0.5, 1); // priority 1, 0.5kg each
wp.addBin('BIN-B', 'WIDGET', 30, 0.5, 3); // priority 3
wp.addBin('BIN-C', 'GADGET', 10, 2.0, 2); // priority 2, 2kg each
wp.addBin('BIN-D', 'GADGET', 5, 2.0, 1); // priority 1
/... |
// After ORD1: BIN-A=0, BIN-B=25, BIN-C=7, BIN-D=0
// Order: 60 WIDGETs (only 25 available in BIN-B) + weight limit
// WIDGETs: BIN-B(25 remaining). At 28.5kg + 25*0.5=12.5 = 41kg. All 25 fit.
// Still need 35 more but no bins. Unfulfilled.
const r2 = wp.pickOrder('ORD2', [{ sku: 'WIDGET', qtyRequested: 60 }]) as Pick... | code_purpose_understanding |
31 | devbench-code-purpose-understanding | typescript | interface Account {
id: string;
balance: number;
dailyTransferred: number;
lastTransferDay: number;
}
interface TransferAudit {
from: string;
to: string;
gross: number;
fee: number;
net: number;
day: number;
status: string;
reason?: string;
}
class BankingService {
... | transfer(fromId: string, toId: string, amount: number, day: number): TransferAudit {
const from = this.accounts.get(fromId);
const to = this.accounts.get(toId);
if (!from || !to) {
const audit: TransferAudit = { from: fromId, to: toId, gross: amount, fee: 0, net: 0, day, status: ... | }
const assert = require('assert');
const bank = new BankingService(1000, 0.02, 5);
bank.addAccount('A', 500);
bank.addAccount('B', 200);
// Normal transfer: amount=100, fee=max(2, 5)=5, total debit=105
const r1 = bank.transfer('A', 'B', 100, 1);
assert.strictEqual(r1.status, 'success');
assert.strictEqual(r1.fee, 5... | // A has transferred 400 on day 1 already (100+300). Try 700 more -> 1100 > 1000 limit
const r3 = bank.transfer('A', 'B', 700, 1);
assert.strictEqual(r3.status, 'failed');
assert.strictEqual(r3.reason, 'daily_limit_exceeded');
// New day resets limit
const r4 = bank.transfer('B', 'A', 500, 2);
assert.strictEqual(r4.st... | code_purpose_understanding |
32 | devbench-code-purpose-understanding | typescript | interface Payment {
month: number;
principal: number;
interest: number;
penalty: number;
remaining: number;
}
class LoanAccount {
originalPrincipal: number;
principal: number;
annualRate: number;
termMonths: number;
earlyPenaltyRate: number; // fraction of remaining principal
... | makePayment(extra: number = 0): Payment | { success: false; reason: string } {
if (this.closed) return { success: false, reason: 'closed' };
const interest = Math.round(this.principal * this.monthlyRate() * 100) / 100;
const scheduled = this.scheduledPayment();
const principalPortio... | }
const assert = require('assert');
// $10,000 loan, 12% annual (1%/month), 12 months, 5% early penalty, min 3 months
const loan = new LoanAccount(10000, 0.12, 12, 0.05, 3);
const sched = loan.scheduledPayment();
assert.strictEqual(sched, 888.49);
// Normal payment month 1: interest = 100, principal = 788.49
const p... | // Regular payment month 2
const p2b = loan.makePayment() as Payment;
assert.strictEqual(p2b.month, 2);
assert.strictEqual(p2b.interest, 92.12); // 9211.51 * 0.01
// Regular payment month 3
const p3 = loan.makePayment() as Payment;
assert.strictEqual(p3.month, 3);
// Now early repayment allowed (month 4, monthsPaid w... | code_purpose_understanding |
33 | devbench-code-purpose-understanding | typescript | interface CreditEvent {
type: 'payment_ontime' | 'payment_late' | 'default' | 'inquiry' | 'account_opened';
timestamp: number; // months since account creation
amount?: number;
}
interface ScoreBreakdown {
paymentHistory: number;
creditUtilization: number;
accountAge: number;
inquiryPenalt... | calculateScore(currentMonth: number): ScoreBreakdown {
// Payment history
let paymentRaw = 0;
for (const e of this.events) {
const age = currentMonth - e.timestamp;
const decay = Math.pow(this.decayFactor, age);
if (e.type === 'payment_ontime') paymentRaw ... | }
const assert = require('assert');
const scorer = new CreditScorer(10000, 0.95);
scorer.addEvent({ type: 'payment_ontime', timestamp: 1 });
scorer.addEvent({ type: 'payment_ontime', timestamp: 2 });
scorer.addEvent({ type: 'payment_ontime', timestamp: 3 });
scorer.setBalance(1000); // 10% utilization
const s1 = sco... | // Build up more history (months 5 through 48 = lots of on-time payments)
for (let m = 5; m <= 48; m++) {
scorer.addEvent({ type: 'payment_ontime', timestamp: m });
}
const s2 = scorer.calculateScore(48);
assert.strictEqual(s2.creditUtilization, 300);
assert.ok(s2.paymentHistory > 300); // many on-time payments wit... | code_purpose_understanding |
34 | devbench-code-purpose-understanding | typescript | interface Item {
name: string;
durability: number; // 0-100, item breaks at 0
stackable: boolean;
quantity: number;
}
interface CraftingRecipe {
output: string;
outputDurability: number;
ingredients: { name: string; quantity: number }[];
requiresMinDurability: number; // each ingre... | craft(outputName: string): { success: boolean; slot?: number; reason?: string; consumed?: { name: string; qty: number; fromSlot: number }[]; missing?: { name: string; have: number; need: number } } {
const recipe = this.recipes.get(outputName);
if (!recipe) return { success: false, reason: 'unknown_... | }
const assert = require('assert');
const inv = new GameInventory(6);
inv.addRecipe({
output: 'iron_sword',
outputDurability: 100,
ingredients: [{ name: 'iron', quantity: 3 }, { name: 'wood', quantity: 1 }],
requiresMinDurability: 20,
});
inv.addItem('iron', 50, true, 2); // slot 0: iron x2, dur 50... | // Craft again: not enough iron (only slot 2 left with dur 15, below min 20)
const r2 = inv2.craft('iron_sword');
assert.strictEqual(r2.success, false);
assert.strictEqual(r2.reason, 'insufficient_materials');
assert.strictEqual(r2.missing!.name, 'iron');
assert.strictEqual(r2.missing!.have, 0); // dur 15 < 20
// Unkn... | code_purpose_understanding |
35 | devbench-code-purpose-understanding | typescript | interface LeaderboardEntry {
playerId: string;
score: number;
submittedAt: number;
flagged: boolean;
session: string;
}
class Leaderboard {
entries: LeaderboardEntry[] = [];
sessions: Map<string, { playerId: string; startedAt: number; maxScore: number }> = new Map();
maxScorePerMinute: ... | submitScore(playerId: string, sessionId: string, score: number, submittedAt: number): { success: boolean; reason?: string; entry?: LeaderboardEntry; rank?: number } {
const session = this.sessions.get(sessionId);
if (!session || session.playerId !== playerId) {
return { success: false, r... | }
const assert = require('assert');
const lb = new Leaderboard(100, 3); // max 100 pts/min, top 3
lb.startSession('p1', 's1', 0);
lb.startSession('p2', 's2', 0);
lb.startSession('p3', 's3', 0);
// Normal submission: 200 pts in 5 min = 40/min, OK
const r1 = lb.submitScore('p1', 's1', 200, 300);
assert.strictEqual(r1.... | // Score not improved
const r4 = lb.submitScore('p1', 's1', 150, 400);
assert.strictEqual(r4.success, false);
assert.strictEqual(r4.reason, 'score_not_improved');
// Score improved replaces
const r5 = lb.submitScore('p1', 's1', 250, 600);
assert.strictEqual(r5.success, true);
assert.strictEqual(r5.rank, 1);
assert.str... | code_purpose_understanding |
36 | devbench-code-purpose-understanding | typescript | interface Player {
id: string;
elo: number;
partyId: string | null;
queuedAt: number;
}
interface MatchResult {
matched: boolean;
teams?: [string[], string[]];
avgElo?: [number, number];
reason?: string;
}
class MatchmakingQueue {
queue: Player[] = [];
teamSize: number;
elo... | tryMatch(now: number): MatchResult {
if (this.queue.length < this.teamSize * 2) {
return { matched: false, reason: 'not_enough_players' };
}
// Compute effective ranges
const withRange = this.queue.map(p => ({
...p,
effectiveRange: Math.min(
... | }
const assert = require('assert');
const mm = new MatchmakingQueue(2, 50, 10, 200); // 2v2, range 50, +10/min, max 200
mm.enqueue({ id: 'a', elo: 1000, partyId: null, queuedAt: 0 });
mm.enqueue({ id: 'b', elo: 1020, partyId: null, queuedAt: 0 });
mm.enqueue({ id: 'c', elo: 1040, partyId: null, queuedAt: 0 });
mm.en... | // Incompatible: two clusters too far apart at time 0
const mm3 = new MatchmakingQueue(2, 30, 5, 300);
mm3.enqueue({ id: 'p1', elo: 1000, partyId: null, queuedAt: 0 });
mm3.enqueue({ id: 'p2', elo: 1010, partyId: null, queuedAt: 0 });
mm3.enqueue({ id: 'p3', elo: 1200, partyId: null, queuedAt: 0 });
mm3.enqueue({ id: '... | code_purpose_understanding |
37 | devbench-code-purpose-understanding | typescript | interface NotificationPrefs {
channels: Set<string>; // 'email' | 'sms' | 'push'
quietHoursStart: number; // hour 0-23
quietHoursEnd: number; // hour 0-23 (wraps around midnight)
maxPerHour: number;
}
interface AppNotification {
id: string;
channel: string;
priority: 'low' | 'm... | send(userId: string, notif: AppNotification): DeliveryResult {
const prefs = this.prefs.get(userId);
if (!prefs) return { delivered: false, reason: 'unknown_user' };
if (!prefs.channels.has(notif.channel)) {
return { delivered: false, reason: 'channel_disabled' };
}
... | }
const assert = require('assert');
const ns = new NotificationService();
ns.setPreferences('u1', {
channels: new Set(['email', 'push']),
quietHoursStart: 22,
quietHoursEnd: 7, // 10pm - 7am
maxPerHour: 2,
});
// Normal delivery (noon = hour 12)
const r1 = ns.send('u1', { id: 'n1', channel: 'email... | // Quiet hours (23:00 UTC = 82800 seconds)
const r3 = ns.send('u1', { id: 'n3', channel: 'email', priority: 'medium', message: 'late', timestamp: 82800 });
assert.strictEqual(r3.delivered, false);
assert.strictEqual(r3.batched, true);
assert.strictEqual(r3.reason, 'quiet_hours');
// Critical bypasses quiet hours
const... | code_purpose_understanding |
38 | devbench-code-purpose-understanding | typescript | interface Alert {
id: string;
severity: 'info' | 'warning' | 'error' | 'critical';
source: string;
message: string;
timestamp: number;
}
interface EscalationState {
alertId: string;
currentLevel: number; // 0=initial, 1=team_lead, 2=manager, 3=director
acknowledged: boolean;
ackn... | receiveAlert(alert: Alert): { created: boolean; level?: number; suppressed: boolean } {
const lastTime = this.recentAlerts.get(alert.source);
if (lastTime !== undefined && alert.timestamp - lastTime < this.suppressWindow) {
if (alert.severity !== 'critical') {
return { cr... | }
const assert = require('assert');
const am = new AlertManager(60, 120, 30); // 60s cooldown, 120s auto-escalate, 30s suppress
// Normal alert
const a1 = am.receiveAlert({ id: 'a1', severity: 'warning', source: 'cpu', message: 'high', timestamp: 100 });
assert.strictEqual(a1.created, true);
assert.strictEqual(a1.le... | // Auto-escalate after 120s: a1 created at 100, check at 220
// a3 created at 125 with level 2, 220-125=95 < 120 so a3 won't escalate yet
const esc1 = am.checkEscalations(220);
assert.ok(esc1.includes('a1'));
assert.strictEqual(am.states.get('a1')!.currentLevel, 1);
assert.ok(!esc1.includes('a3')); // not enough time f... | code_purpose_understanding |
39 | devbench-code-purpose-understanding | typescript | interface Permission {
resource: string;
action: string; // 'read' | 'write' | 'delete' | 'admin'
}
interface Role {
name: string;
permissions: Permission[];
inherits: string[]; // parent role names
}
class RBACManager {
roles: Map<string, Role> = new Map();
userRoles: Map<string, Set<s... | _getAllPermissions(roleName: string, visited: Set<string> = new Set()): Permission[] {
if (visited.has(roleName)) return [];
visited.add(roleName);
const role = this.roles.get(roleName);
if (!role) return [];
const perms = [...role.permissions];
for (const parent of ... | }
const assert = require('assert');
const rbac = new RBACManager();
rbac.addRole('viewer', [{ resource: 'docs', action: 'read' }]);
rbac.addRole('editor', [{ resource: 'docs', action: 'write' }], ['viewer']);
rbac.addRole('admin', [{ resource: '*', action: 'admin' }]);
rbac.assignRole('alice', 'editor');
rbac.assign... | // Admin wildcard: admin on * implies everything
const r4 = rbac.checkAccess('charlie', 'docs', 'delete');
assert.strictEqual(r4.allowed, true);
const r5 = rbac.checkAccess('charlie', 'servers', 'write');
assert.strictEqual(r5.allowed, true);
// Explicit deny overrides role grant
rbac.addDeny('charlie', { resource: 's... | code_purpose_understanding |
40 | devbench-code-purpose-understanding | typescript | interface RateLimitTier {
name: string;
requestsPerMinute: number;
requestsPerHour: number;
burstSize: number; // max requests in any 5-second window
}
interface RequestLog {
timestamp: number; // unix seconds
endpoint: string;
allowed: boolean;
}
class APIRateLimiter {
... | checkRequest(clientId: string, endpoint: string, now: number): {
allowed: boolean;
reason?: string;
remaining?: { burst: number; minute: number; hour: number };
retryAfter?: number;
} {
const tierName = this.clientTiers.get(clientId);
if (!tierName) return { allow... | }
const assert = require('assert');
const rl = new APIRateLimiter();
rl.addTier({ name: 'basic', requestsPerMinute: 5, requestsPerHour: 20, burstSize: 3 });
rl.registerClient('c1', 'basic');
// 3 requests in burst window
const r1 = rl.checkRequest('c1', '/api/data', 1000);
assert.strictEqual(r1.allowed, true);
asser... | // Rejected request does NOT count toward limits
// After burst window expires (t > 1005), burst resets
const r5 = rl.checkRequest('c1', '/api/data', 1006);
assert.strictEqual(r5.allowed, true);
assert.strictEqual(r5.remaining!.minute, 1); // 4 allowed so far (r1,r2,r3,r5), limit 5
// Fill minute quota
const r6 = rl.c... | code_purpose_understanding |
41 | devbench-code-purpose-understanding | typescript | interface Evt { type: string; id: string; v: number; amt: number }
interface Acct { id: string; bal: number; frozen: boolean; v: number }
class Store {
evts: Evt[] = [];
append(e: Evt): boolean {
const last = this.evts.filter(x => x.id === e.id);
if (last.length > 0 && last[last.length-1].v + 1 ... | project(id: string): Acct {
const s: Acct = { id, bal: 0, frozen: false, v: 0 };
for (const e of this.evts.filter(x => x.id === id)) {
if (e.type === 'dep' && !s.frozen) s.bal += e.amt;
else if (e.type === 'wd' && !s.frozen && s.bal >= e.amt) s.bal -= e.amt;
else ... | }
const st = new Store();
st.append({type:'dep',id:'a',v:1,amt:100});
st.append({type:'dep',id:'a',v:2,amt:50});
st.append({type:'wd',id:'a',v:3,amt:30});
const s1 = st.project('a');
if (s1.bal !== 120) throw new Error('bal');
if (s1.v !== 3) throw new Error('v');
| st.append({type:'freeze',id:'a',v:4,amt:0});
st.append({type:'dep',id:'a',v:5,amt:999});
const s2 = st.project('a');
if (s2.bal !== 120) throw new Error('frozen deposit');
if (!s2.frozen) throw new Error('frozen');
st.append({type:'unfreeze',id:'a',v:6,amt:0});
st.append({type:'wd',id:'a',v:7,amt:200});
const s3 = st.p... | code_purpose_understanding |
42 | devbench-code-purpose-understanding | typescript | interface Step { name: string; exec: () => boolean; comp: () => void }
interface SagaRes { ok: boolean; done: string[]; undone: string[]; failed: string | null }
class Saga {
steps: Step[] = [];
log: string[] = [];
add(s: Step) { this.steps.push(s); }
| run(): SagaRes {
const done: string[] = [];
for (const s of this.steps) {
if (s.exec()) {
done.push(s.name);
this.log.push('exec:' + s.name);
} else {
this.log.push('fail:' + s.name);
const undone: string[] = [];... | }
const s1 = new Saga();
const o: string[] = [];
s1.add({name:'A',exec:()=>(o.push('eA'),true),comp:()=>o.push('cA')});
s1.add({name:'B',exec:()=>(o.push('eB'),true),comp:()=>o.push('cB')});
s1.add({name:'C',exec:()=>(o.push('eC'),true),comp:()=>o.push('cC')});
const r1 = s1.run();
if (!r1.ok || r1.done.length!==3) thr... | const s2 = new Saga();
const o2: string[] = [];
s2.add({name:'X',exec:()=>(o2.push('eX'),true),comp:()=>o2.push('cX')});
s2.add({name:'Y',exec:()=>(o2.push('eY'),true),comp:()=>o2.push('cY')});
s2.add({name:'Z',exec:()=>(o2.push('eZ'),false),comp:()=>o2.push('cZ')});
const r2 = s2.run();
if (r2.ok) throw new Error('fai... | code_purpose_understanding |
43 | devbench-code-purpose-understanding | typescript | type Res = { ok: boolean; err?: string }
interface Order { items: {sku:string;qty:number;price:number}[]; total: number; status: 'open'|'cancelled'; ver: number }
class Orders {
data: Map<string, Order> = new Map();
ver: Map<string, number> = new Map();
private nv(id:string) { const v=(this.ver.get(id)||0)+... | exec(type: string, id: string, p: any): Res {
if (type==='create') {
if (this.data.has(id)) return {ok:false,err:'exists'};
const it=p.items as {sku:string;qty:number;price:number}[];
if (!it||!it.length) return {ok:false,err:'empty'};
if (it.some((x:any)=>x.q... | }
const svc = new Orders();
svc.exec('create','O1',{items:[{sku:'A',qty:2,price:10},{sku:'B',qty:1,price:25}]});
const o1 = svc.data.get('O1')!;
if (o1.total!==45) throw new Error('total');
svc.exec('update_qty','O1',{sku:'A',qty:5});
if (svc.data.get('O1')!.total!==75) throw new Error('upd');
| if (svc.exec('create','O1',{items:[{sku:'X',qty:1,price:1}]}).err!=='exists') throw new Error('dup');
svc.exec('cancel','O1',{});
if (svc.exec('update_qty','O1',{sku:'A',qty:1}).err!=='closed') throw new Error('cancelled');
if (svc.exec('cancel','O1',{}).err!=='already') throw new Error('2xcancel');
if (svc.exec('creat... | code_purpose_understanding |
44 | devbench-code-purpose-understanding | typescript | interface Approver { id: string; max: number }
interface Vote { by: string; ok: boolean; at: number }
interface Doc { amt: number; status: 'review'|'approved'|'rejected'; votes: Vote[]; need: number }
class Pipeline {
approvers: Map<string,Approver> = new Map();
docs: Map<string,Doc> = new Map();
t = 0;
... | decide(id: string, who: string, approve: boolean): {ok:boolean; why?:string; status?:string} {
this.t++;
const d = this.docs.get(id);
if (!d) return {ok:false, why:'no_doc'};
if (d.status !== 'review') return {ok:false, why:'not_review'};
const a = this.approvers.get(who);
... | }
const p = new Pipeline();
p.reg({id:'r1',max:100}); p.reg({id:'m1',max:5000}); p.reg({id:'d1',max:50000});
p.submit('D1', 3000, 2);
if (p.decide('D1','r1',true).why !== 'no_authority') throw new Error('auth');
const v1 = p.decide('D1','m1',true);
if (!v1.ok || v1.status !== 'review') throw new Error('1of2');
const v2... | if (p.decide('D1','m1',true).why !== 'not_review') throw new Error('post-approve');
p.submit('D2', 50, 3);
if (p.decide('D2','r1',false).status !== 'rejected') throw new Error('reject');
if (p.decide('D2','m1',true).why !== 'not_review') throw new Error('post-reject');
p.submit('D3', 100, 2);
p.decide('D3','r1',true);
... | code_purpose_understanding |
45 | devbench-code-purpose-understanding | typescript | type Sev = 'P1'|'P2'|'P3'; type St = 'open'|'ack'|'resolved';
const SLA: Record<Sev,number> = {P1:15,P2:30,P3:60};
const TRANSITIONS: Record<St,St[]> = {open:['ack'],ack:['resolved'],resolved:[]};
interface Inc { sev:Sev; st:St; who:string; esc:number; created:number }
class IncMgr {
incs: Map<string,Inc> = new Map... | create(id:string, sev:Sev): string {
const who = this.roster[this.idx++ % this.roster.length];
this.incs.set(id, {sev,st:'open',who,esc:0,created:this.now});
return who;
}
transition(id:string, to:St): boolean {
const i = this.incs.get(id);
if (!i || !TRANSITIONS[i.st... | }
const m = new IncMgr(['alice','bob','carol']);
m.time(0);
if (m.create('I1','P1') !== 'alice') throw new Error('assign');
m.time(10);
if (!m.slaOk('I1')) throw new Error('sla10');
m.time(16);
if (m.slaOk('I1')) throw new Error('sla16');
m.transition('I1','ack');
if (!m.slaOk('I1')) throw new Error('acked');
| if (m.transition('I1','open')) throw new Error('bad trans');
m.transition('I1','resolved');
if (m.escalate('I1') !== null) throw new Error('esc resolved');
m.time(100); m.create('I2','P2');
m.time(131);
if (m.slaOk('I2')) throw new Error('P2 breach');
const e = m.escalate('I2');
if (e !== 'carol') throw new Error('rota... | code_purpose_understanding |
46 | devbench-code-purpose-understanding | typescript | type SR = 'pass'|'fail'|'skip';
interface Stage { name:string; run:()=>SR; rb:()=>void; dep:boolean }
interface Run { stages:{name:string;r:SR;rb:boolean}[]; ok:boolean }
class Pipe {
stages: Stage[] = [];
add(s: Stage) { this.stages.push(s); }
| exec(): Run {
const out: {name:string;r:SR;rb:boolean}[] = [];
const ran: number[] = [];
let fail = false;
for (let i = 0; i < this.stages.length; i++) {
const s = this.stages[i];
if (fail && s.dep) { out.push({name:s.name,r:'skip',rb:false}); continue; }
... | }
const p = new Pipe();
p.add({name:'build',run:()=>'pass',rb:()=>{},dep:false});
p.add({name:'test',run:()=>'pass',rb:()=>{},dep:true});
p.add({name:'deploy',run:()=>'pass',rb:()=>{},dep:true});
const r1 = p.exec();
if (!r1.ok || r1.stages.some(s=>s.rb)) throw new Error('ok');
| const p2 = new Pipe();
const rb: string[] = [];
p2.add({name:'build',run:()=>'pass',rb:()=>rb.push('B'),dep:false});
p2.add({name:'test',run:()=>'fail',rb:()=>rb.push('T'),dep:true});
p2.add({name:'deploy',run:()=>'pass',rb:()=>rb.push('D'),dep:true});
p2.add({name:'notify',run:()=>'pass',rb:()=>rb.push('N'),dep:false}... | code_purpose_understanding |
47 | devbench-code-purpose-understanding | typescript | interface FE { uid:string; step:string; ts:number }
class Funnel {
evts: FE[] = [];
steps: string[];
win: number;
constructor(steps: string[], win: number) { this.steps=steps; this.win=win; }
add(e: FE) { this.evts.push(e); }
| analyze(): { counts:number[]; rates:number[]; drops:number[] } {
const paths: Map<string, number[]> = new Map();
for (const uid of new Set(this.evts.map(e=>e.uid))) {
const ue = this.evts.filter(e=>e.uid===uid).sort((a,b)=>a.ts-b.ts);
const times: number[] = [];
l... | }
const f = new Funnel(['visit','signup','buy'], 86400000);
f.add({uid:'A',step:'visit',ts:1000}); f.add({uid:'A',step:'signup',ts:2000}); f.add({uid:'A',step:'buy',ts:5000});
f.add({uid:'B',step:'visit',ts:1500}); f.add({uid:'B',step:'signup',ts:3000});
f.add({uid:'C',step:'visit',ts:2000});
const r = f.analyze();
if ... | const f2 = new Funnel(['a','b'],100);
f2.add({uid:'X',step:'a',ts:0}); f2.add({uid:'X',step:'b',ts:200});
const r2 = f2.analyze();
if (r2.counts[1]!==0) throw new Error('window');
const f3 = new Funnel(['A','B','C'],100000);
f3.add({uid:'U',step:'C',ts:1}); f3.add({uid:'U',step:'A',ts:2}); f3.add({uid:'U',step:'B',ts:3... | code_purpose_understanding |
48 | devbench-code-purpose-understanding | typescript | interface Obs { variant:string; converted:boolean; value:number }
interface ExpRes { ready:boolean; winner:string|null; stats:Record<string,{n:number;conv:number;rate:number}> }
class ABTest {
variants: string[];
minN: number;
obs: Obs[] = [];
constructor(variants:string[], minN:number) { this.variants=... | evaluate(): ExpRes {
const stats: Record<string,{n:number;conv:number;rate:number}> = {};
for (const v of this.variants) {
const vo = this.obs.filter(o=>o.variant===v);
const conv = vo.filter(o=>o.converted).length;
stats[v] = { n:vo.length, conv, rate: vo.length>... | }
const e = new ABTest(['ctrl','treat'], 5);
for (let i=0;i<3;i++) { e.record({variant:'ctrl',converted:false,value:0}); e.record({variant:'treat',converted:true,value:1}); }
if (e.evaluate().ready) throw new Error('not ready');
for (let i=0;i<7;i++) { e.record({variant:'ctrl',converted:false,value:0}); e.record({varia... | if (!r.winner||r.winner!=='treat') throw new Error('winner');
if (r.stats['treat'].rate!==1) throw new Error('rate');
if (e.record({variant:'bad',converted:true,value:0})) throw new Error('invalid');
const e2 = new ABTest(['A','B'],5);
for (let i=0;i<10;i++) { e2.record({variant:'A',converted:i%2===0,value:1}); e2.reco... | code_purpose_understanding |
49 | devbench-code-purpose-understanding | typescript | interface RLRes { allowed:boolean; remaining:number; retryMs:number }
class RateLimiter {
max: number; winMs: number; penMs: number;
hits: Map<string,number[]> = new Map();
pens: Map<string,number> = new Map();
viols: Map<string,number> = new Map();
constructor(max:number, winMs:number, penMs:number... | check(cid: string, now: number): RLRes {
const pe = this.pens.get(cid) || 0;
if (now < pe) return {allowed:false, remaining:0, retryMs:pe-now};
const ts = (this.hits.get(cid)||[]).filter(t => t > now-this.winMs);
this.hits.set(cid, ts);
if (ts.length >= this.max) {
... | }
const l = new RateLimiter(3, 1000, 500);
if (!l.check('u',100).allowed) throw new Error('1st');
if (!l.check('u',200).allowed) throw new Error('2nd');
if (!l.check('u',300).allowed) throw new Error('3rd');
const r4 = l.check('u',400);
if (r4.allowed) throw new Error('limited');
if (r4.retryMs!==500) throw new Error('... | const r5 = l.check('u',700);
if (r5.allowed) throw new Error('still pen');
if (r5.retryMs!==200) throw new Error('rem:'+r5.retryMs);
const r6 = l.check('u',1500);
if (!r6.allowed) throw new Error('expired');
const l2 = new RateLimiter(1,100,200);
l2.check('X',0); l2.check('X',10); // viol 1, pen=200
l2.check('X',250); ... | code_purpose_understanding |
50 | devbench-code-purpose-understanding | typescript | type NT = 'start'|'task'|'decision'|'end';
interface WNode { id:string; type:NT; fn?:(c:any)=>void; cond?:(c:any)=>boolean; yes?:string; no?:string; next?:string }
interface Trace { id:string; type:NT; branch?:'T'|'F' }
class WF {
nodes: Map<string,WNode> = new Map();
startId: string|null = null;
add(n: WNo... | run(ctx: any): {trace:Trace[];ctx:any;done:boolean;err?:string} {
if (!this.startId) return {trace:[],ctx,done:false,err:'no_start'};
const trace: Trace[] = []; let cur: string|null = this.startId;
const seen = new Set<string>();
while (cur) {
const n = this.nodes.get(cur... | }
const w = new WF();
w.add({id:'s',type:'start',fn:c=>{c.ok=true},next:'d'});
w.add({id:'d',type:'decision',cond:c=>c.amt>0,yes:'p',no:'r'});
w.add({id:'p',type:'task',fn:c=>{c.processed=true},next:'e'});
w.add({id:'r',type:'task',fn:c=>{c.rejected=true},next:'e'});
w.add({id:'e',type:'end'});
const r1 = w.run({amt:10... | const w2 = new WF();
w2.add({id:'t',type:'task',next:'e2'});
if (w2.run({}).done) throw new Error('no start');
const w3 = new WF();
w3.add({id:'s',type:'start',next:'x'});
if (w3.run({}).done||!w3.run({}).err?.includes('missing')) throw new Error('missing');
const w4 = new WF();
w4.add({id:'s',type:'start',next:'s'});
... | code_purpose_understanding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.