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 | javascript | const fs = require('fs');
const os = require('os');
const path = require('path');
const assert = require('assert');
function writeStrictJson(filePath, value) {
const body = JSON.stringify(value, null, 2);
const fd = fs.openSync(filePath, 'wx', 0o600);
try {
fs.writeFileSync(fd, body, { encoding: 'utf8' });
... | `Use fs.openSync(filePath, 'wx', 0o600) to create a new file exclusively and fail with EEXIST instead of overwriting.
Serialize value with JSON.stringify(value, null, 2), write UTF-8 text through fs.writeFileSync(fd, body, { encoding: 'utf8' }), and always close the descriptor in a finally block with fs.closeSync(fd).
... | ;
assert.strictEqual(typeof writeStrictJson.doc, 'string');
assert.ok(writeStrictJson.doc.includes('fs.openSync'));
assert.ok(writeStrictJson.doc.includes("'wx'"));
assert.ok(writeStrictJson.doc.includes('fs.closeSync'));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'db-doc-'));
const file = path.join(dir, 'payl... | for (const term of [
'JSON.stringify(value, null, 2)',
'fs.writeFileSync(fd, body',
"{ encoding: 'utf8' }",
'Buffer.byteLength(body',
'EEXIST',
'0o600',
'finally',
'normal Node fs exceptions'
]) {
assert.ok(writeStrictJson.doc.includes(term), 'doc missing ' + term);
}
const docFile = path.join(fs.mkdt... | api_usage |
2 | devbench-api-usage | javascript | const { Buffer } = require('buffer');
const assert = require('assert');
function decodeLenientBase64(input) {
return Buffer.from(input, 'base64').toString('utf8');
}
// Fill in precise API documentation for decodeLenientBase64.
// The executable implementation above is the source of truth.
decodeLenientBase64.doc =... | `Decode input with Buffer.from(input, 'base64') and return the bytes as a UTF-8 string via toString('utf8').
This deliberately relies on Node's lenient base64 decoder: missing padding, ASCII whitespace, and non-base64 characters are ignored/skipped rather than rejected.
The function performs no validation and normally ... | ;
assert.strictEqual(typeof decodeLenientBase64.doc, 'string');
assert.ok(decodeLenientBase64.doc.includes("Buffer.from(input, 'base64')"));
assert.ok(decodeLenientBase64.doc.includes("toString('utf8')"));
assert.ok(decodeLenientBase64.doc.includes('lenient'));
assert.strictEqual(decodeLenientBase64('SGVsbG8='), 'Hel... | for (const term of [
'missing padding',
'ASCII whitespace',
'non-base64 characters',
'ignored/skipped',
'no validation',
'does not throw',
'all-garbage input',
'empty string'
]) {
assert.ok(decodeLenientBase64.doc.includes(term), 'doc missing ' + term);
}
assert.strictEqual(decodeLenientBase64(''), ''... | api_usage |
3 | devbench-api-usage | javascript | const { URL } = require('url');
const assert = require('assert');
function collectQueryValues(urlStr) {
const url = new URL(urlStr);
const result = {};
for (const [key, value] of url.searchParams) {
if (!Object.prototype.hasOwnProperty.call(result, key)) result[key] = [];
result[key].push(value);
}
r... | `Parse urlStr with the WHATWG URL constructor new URL(urlStr), then iterate url.searchParams to collect every [key, value] pair.
Duplicate parameter names are preserved in insertion order by pushing each decoded value into an array, including empty-string values from ?name= or bare ?name.
URLSearchParams percent-decode... | ;
assert.strictEqual(typeof collectQueryValues.doc, 'string');
assert.ok(collectQueryValues.doc.includes('new URL(urlStr)'));
assert.ok(collectQueryValues.doc.includes('url.searchParams'));
assert.ok(collectQueryValues.doc.includes('Duplicate'));
const r = collectQueryValues('https://x.test/?tag=a&tag=b&q=hello+world... | for (const term of [
'WHATWG URL',
'[key, value]',
'insertion order',
'decoded value',
'empty-string values',
'percent-decodes',
'+ in the query as a space',
'TypeError'
]) {
assert.ok(collectQueryValues.doc.includes(term), 'doc missing ' + term);
}
const r2 = collectQueryValues('https://x.test/?a=1&a... | api_usage |
4 | devbench-api-usage | javascript | const path = require('path');
// Implement a function that normalizes a sequence of path segments.
// IMPORTANT: Unlike path.join, if any segment is an absolute path,
// all preceding segments are DISCARDED (like path.resolve but
// without using cwd — treat the first segment as the base).
// The result must be normal... | if (segments.length === 0) return '.';
let resolved = segments[0];
for (let i = 1; i < segments.length; i++) {
if (path.isAbsolute(segments[i])) {
resolved = segments[i];
} else {
resolved = path.join(resolved, segments[i]);
}
}
return path.normalize(resolved);
| }
// If a segment is absolute, preceding segments are discarded
if (resolveSegments('/usr', 'local', '/etc', 'hosts') !== '/etc/hosts') {
throw new Error('absolute reset failed');
}
if (resolveSegments('a', 'b', 'c') !== 'a/b/c') {
throw new Error('relative join failed');
}
if (resolveSegments('/a', 'b', '..', 'c'... | // Single segment
if (resolveSegments('/root') !== '/root') throw new Error('single absolute');
if (resolveSegments('rel') !== 'rel') throw new Error('single relative');
// Empty segments case
if (resolveSegments() !== '.') throw new Error('no segments');
// Multiple absolute resets
const r = resolveSegments('/a', '/... | api_usage |
5 | devbench-api-usage | javascript | const util = require('util');
const assert = require('assert');
function scaleLater(n, callback) {
setImmediate(() => callback(null, n * 2));
}
scaleLater[util.promisify.custom] = (n) => Promise.resolve(n * 3);
// Fill in precise API documentation for scaleLater.
// The executable implementation above is the source... | `scaleLater is a Node-style callback API: it schedules setImmediate and calls callback(null, n * 2), so callback consumers receive the doubled value.
It also defines scaleLater[util.promisify.custom], the symbol used by util.promisify, as a custom Promise-returning function that resolves to n * 3 instead of wrapping th... | ;
assert.strictEqual(typeof scaleLater.doc, 'string');
assert.ok(scaleLater.doc.includes('util.promisify.custom'));
assert.ok(scaleLater.doc.includes('callback(null'));
assert.ok(scaleLater.doc.includes('Promise'));
const scaleLaterAsync = util.promisify(scaleLater);
scaleLater(5, (err, value) => {
assert.ifError(e... | for (const term of [
'Node-style callback API',
'setImmediate',
'n * 2',
'symbol used by util.promisify',
'n * 3',
'instead of wrapping the callback behavior',
'does not change the original callback API',
'first argument convention'
]) {
assert.ok(scaleLater.doc.includes(term), 'doc missing ' + term);... | api_usage |
6 | devbench-api-usage | javascript | const { Transform } = require('stream');
const assert = require('assert');
class ReverseCollectStream extends Transform {
constructor() {
super({ decodeStrings: true });
this._chunks = [];
}
_transform(chunk, encoding, callback) {
this._chunks.push(Buffer.from(chunk));
callback();
}
_flush(ca... | `ReverseCollectStream is a stream.Transform subclass constructed with decodeStrings: true, so written strings arrive at _transform as Buffer chunks.
_transform buffers Buffer.from(chunk) in this._chunks and calls callback() without pushing data, meaning output is intentionally delayed until stream finalization.
_flush ... | ;
assert.strictEqual(typeof ReverseCollectStream.doc, 'string');
assert.ok(ReverseCollectStream.doc.includes('stream.Transform'));
assert.ok(ReverseCollectStream.doc.includes('_transform'));
assert.ok(ReverseCollectStream.doc.includes('_flush'));
const rs = new ReverseCollectStream();
let output = '';
rs.on('data', c... | for (const term of [
'decodeStrings: true',
'Buffer chunks',
'Buffer.from(chunk)',
'calls callback() without pushing data',
'delayed until stream finalization',
'Buffer.concat(this._chunks)',
'pushes a Buffer',
'passing an error to those callbacks'
]) {
assert.ok(ReverseCollectStream.doc.includes(term... | api_usage |
7 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
function deriveScryptKey(password, saltHex) {
const salt = saltHex === undefined ? crypto.randomBytes(16) : Buffer.from(saltHex, 'hex');
if (salt.length !== 16) throw new RangeError('salt must be 16 bytes');
const options = { N: 16384, r: 8, p: ... | `Derive a 32-byte Buffer with crypto.scryptSync(password, salt, 32, { N: 16384, r: 8, p: 1 }).
If saltHex is undefined, generate a 16-byte salt with crypto.randomBytes(16); otherwise decode the provided hex string with Buffer.from(saltHex, 'hex') and require the decoded salt length to be exactly 16 bytes.
The same pass... | ;
assert.strictEqual(typeof deriveScryptKey.doc, 'string');
assert.ok(deriveScryptKey.doc.includes('crypto.scryptSync'));
assert.ok(deriveScryptKey.doc.includes('crypto.randomBytes(16)'));
assert.ok(deriveScryptKey.doc.includes("Buffer.from(saltHex, 'hex')"));
const saltHex = '0123456789abcdef0123456789abcdef';
const... | for (const term of [
'32-byte Buffer',
'{ N: 16384, r: 8, p: 1 }',
'saltHex is undefined',
'16-byte salt',
'decoded salt length',
'exactly 16 bytes',
'same password and salt produce the same key',
'random salt makes calls non-deterministic',
'RangeError before scryptSync is called'
]) {
assert.ok(de... | api_usage |
8 | devbench-api-usage | javascript | const EventEmitter = require('events');
// Create a SafeEmitter class that extends EventEmitter with these behaviors:
// 1. If an 'error' event is emitted and there are NO error listeners
// (other than the internal one), it stores the error in this.lastError
// instead of throwing.
// 2. It tracks the total num... | constructor() {
super();
this.lastError = null;
this.eventCount = 0;
this.setMaxListeners(5);
// Internal error handler to prevent throw
this.on('error', (err) => {
this.lastError = err;
});
}
emit(type, ...args) {
this.eventCount++;
return super.emit(type, ...args);
... | }
const se = new SafeEmitter();
// Should not throw on error
se.emit('error', new Error('test error'));
if (!(se.lastError instanceof Error)) throw new Error('lastError not set');
if (se.lastError.message !== 'test error') throw new Error('wrong error');
// Event counting
se.emit('data', 'hello');
se.emit('data', 'w... | const _se2 = new SafeEmitter();
// Multiple errors overwrite lastError
_se2.emit('error', new Error('first'));
_se2.emit('error', new Error('second'));
if (_se2.lastError.message !== 'second') throw new Error('should be second');
// eventCount includes error events
if (_se2.eventCount !== 2) throw new Error('error co... | api_usage |
9 | devbench-api-usage | javascript | const zlib = require('zlib');
// Implement a compress/decompress pair using zlib.deflateSync and
// zlib.inflateSync (NOT gzip). Requirements:
// - Use compression level 9 (best compression)
// - Use a raw deflate stream (windowBits = -15) for both compress and decompress
// - Return Buffers
// The raw deflate format ... | return zlib.deflateRawSync(data, { level: 9 });
}
function decompressRaw(compressed) {
return zlib.inflateRawSync(compressed);
| }
const original = Buffer.from('hello world hello world hello world');
const compressed = compressRaw(original);
const decompressed = decompressRaw(compressed);
if (!decompressed.equals(original)) throw new Error('round-trip failed');
// Raw deflate should be smaller than original for repetitive data
if (compressed.l... | // Empty input
const _e9 = compressRaw(Buffer.alloc(0));
const _d9 = decompressRaw(_e9);
if (_d9.length !== 0) throw new Error('empty round-trip: ' + _d9.length);
// Verify it's truly raw deflate (no zlib/gzip header)
const _c9 = compressRaw(Buffer.from('test'));
// zlib header starts with 0x78, gzip with 0x1f 0x8b
//... | api_usage |
10 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
function rollingSha256Hex(chunks) {
const hash = crypto.createHash('sha256');
const digests = [];
for (const chunk of chunks) {
hash.update(chunk);
digests.push(hash.copy().digest('hex'));
}
return digests;
}
// Fill in precise API ... | `Create a crypto.Hash with crypto.createHash('sha256'), update it once per chunk, and after each update call hash.copy().digest('hex') to snapshot the current state.
hash.copy() clones the Hash object so digest('hex') finalizes only the clone and does not finalize or mutate the original hash, allowing later chunks to k... | ;
assert.strictEqual(typeof rollingSha256Hex.doc, 'string');
assert.ok(rollingSha256Hex.doc.includes("crypto.createHash('sha256')"));
assert.ok(rollingSha256Hex.doc.includes('hash.copy()'));
assert.ok(rollingSha256Hex.doc.includes("digest('hex')"));
const parts = ['hello', ' ', 'world'];
const got = rollingSha256Hex(... | for (const term of [
'update it once per chunk',
'snapshot the current state',
'finalizes only the clone',
'does not finalize or mutate the original hash',
'keep accumulating',
'64-character lowercase hexadecimal',
'empty chunks array returns []',
'concatenated input in order'
]) {
assert.ok(rollingSh... | api_usage |
11 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
function sha256OfHexBytes(hexStr) {
return crypto.createHash('sha256').update(hexStr, 'hex').digest('hex');
}
// Fill in precise API documentation for sha256OfHexBytes.
// The executable implementation above is the source of truth.
sha256OfHexBytes... | `Hash the raw bytes represented by hexStr, not the ASCII characters of the hex text.
The implementation uses crypto.createHash('sha256').update(hexStr, 'hex').digest('hex'), where the second argument to update is the input encoding and the argument to digest is the output encoding.
Return the 64-character lowercase hex... | ;
assert.strictEqual(typeof sha256OfHexBytes.doc, 'string');
assert.ok(sha256OfHexBytes.doc.includes("update(hexStr, 'hex')"));
assert.ok(sha256OfHexBytes.doc.includes("digest('hex')"));
assert.ok(sha256OfHexBytes.doc.includes('not the ASCII'));
const byteHash = sha256OfHexBytes('ff');
const asciiHash = crypto.create... | for (const term of [
'raw bytes represented by hexStr',
'crypto.createHash(\'sha256\')',
'second argument to update is the input encoding',
'argument to digest is the output encoding',
'64-character lowercase hexadecimal',
'decoded byte sequence',
'normal hex-decoding behavior',
'custom validation'
]) {... | api_usage |
12 | devbench-api-usage | javascript | const { Buffer } = require('buffer');
// Demonstrate Buffer.from's LENIENT base64 decoding.
// Node.js Buffer.from(str, 'base64') silently ignores:
// - Missing padding (no '=' needed)
// - Non-base64 characters (they are skipped)
// - Whitespace
//
// This function takes a potentially malformed base64 string an... | function lenientBase64Decode(input) {
return Buffer.from(input, 'base64').toString('utf-8');
}
|
const assert = require('assert');
// Standard base64 with proper padding
assert.strictEqual(lenientBase64Decode('SGVsbG8='), 'Hello');
// Missing padding — Buffer handles it fine
assert.strictEqual(lenientBase64Decode('SGVsbG8'), 'Hello');
// Non-base64 characters are silently ignored
assert.strictEqual(lenientBase... | // Various forms of 'Hi' in base64 (SGk= or SGk)
assert.strictEqual(lenientBase64Decode('SGk='), 'Hi');
assert.strictEqual(lenientBase64Decode('SGk'), 'Hi');
assert.strictEqual(lenientBase64Decode('S G k'), 'Hi');
// All garbage input => empty buffer => empty string
assert.strictEqual(lenientBase64Decode('!@#$'), ''... | api_usage |
13 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
function timingSafeStringEqual(a, b) {
const left = Buffer.from(a, 'utf8');
const right = Buffer.from(b, 'utf8');
if (left.length !== right.length) return false;
return crypto.timingSafeEqual(left, right);
}
// Fill in precise API documentati... | `Compare two strings by first encoding each with Buffer.from(value, 'utf8'), so length checks are byte-length checks rather than JavaScript character-count checks.
Return false before calling crypto.timingSafeEqual when the Buffer lengths differ, because timingSafeEqual requires equal byte lengths and throws for mismat... | ;
assert.strictEqual(typeof timingSafeStringEqual.doc, 'string');
assert.ok(timingSafeStringEqual.doc.includes("Buffer.from(value, 'utf8')"));
assert.ok(timingSafeStringEqual.doc.includes('crypto.timingSafeEqual'));
assert.ok(timingSafeStringEqual.doc.includes('throws'));
assert.strictEqual(timingSafeStringEqual('hel... | for (const term of [
'byte-length checks',
'rather than JavaScript character-count checks',
'Return false before calling crypto.timingSafeEqual',
'requires equal byte lengths',
'mismatched lengths',
'equal-length Buffers',
'API exception',
'reveals length equality'
]) {
assert.ok(timingSafeStringEqual... | api_usage |
14 | devbench-api-usage | javascript | const { Buffer } = require('buffer');
const assert = require('assert');
function sparseZeroBuffer(size, positionMap) {
const buf = Buffer.alloc(size);
for (const [pos, value] of Object.entries(positionMap)) {
buf[Number(pos)] = value;
}
return buf;
}
// Fill in precise API documentation for sparseZeroBuff... | `Create a zero-filled Buffer of length size with Buffer.alloc(size), not Buffer.allocUnsafe, so every byte starts as 0.
Iterate Object.entries(positionMap), convert each object-key string to a numeric index with Number(pos), and assign the byte value into the Buffer.
Return the mutable Buffer; entries not present in po... | ;
assert.strictEqual(typeof sparseZeroBuffer.doc, 'string');
assert.ok(sparseZeroBuffer.doc.includes('Buffer.alloc(size)'));
assert.ok(sparseZeroBuffer.doc.includes('Buffer.allocUnsafe'));
assert.ok(sparseZeroBuffer.doc.includes('Object.entries(positionMap)'));
const b = sparseZeroBuffer(4, { 1: 0xff, 3: 0xab });
ass... | for (const term of [
'zero-filled Buffer',
'every byte starts as 0',
'object-key string',
'Number(pos)',
'byte value',
'mutable Buffer',
'entries not present in positionMap remain zero',
'no custom bounds or value validation',
'normal Buffer indexed assignment semantics'
]) {
assert.ok(sparseZeroBuf... | api_usage |
15 | devbench-api-usage | javascript | const { Buffer } = require('buffer');
const assert = require('assert');
function sortHexBytewise(hexStrings) {
return hexStrings.slice().sort((a, b) => {
return Buffer.compare(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
});
}
// Fill in precise API documentation for sortHexBytewise.
// The executable imple... | `Return a new sorted array by calling hexStrings.slice() before Array.prototype.sort, so the input array is not mutated.
Each comparator call decodes both strings with Buffer.from(value, 'hex') and passes the Buffers to Buffer.compare, whose negative/zero/positive result is used directly by sort.
Ordering is lexicograp... | ;
assert.strictEqual(typeof sortHexBytewise.doc, 'string');
assert.ok(sortHexBytewise.doc.includes('hexStrings.slice()'));
assert.ok(sortHexBytewise.doc.includes("Buffer.from(value, 'hex')"));
assert.ok(sortHexBytewise.doc.includes('Buffer.compare'));
const input = ['ff', '00', '0a', '80'];
assert.deepStrictEqual(sor... | for (const term of [
'new sorted array',
'input array is not mutated',
'comparator call decodes both strings',
'negative/zero/positive result',
'used directly by sort',
'lexicographic over unsigned byte values',
'not JavaScript string order',
'numeric integer order',
'shorter Buffer sorts first'
]) {
... | api_usage |
16 | devbench-api-usage | javascript | const util = require('util');
const assert = require('assert');
function classifyBuiltInValue(value) {
if (util.types.isDate(value)) return 'date';
if (util.types.isRegExp(value)) return 'regexp';
if (util.types.isMap(value)) return 'map';
if (util.types.isSet(value)) return 'set';
if (util.types.isPromise(v... | `Classify value using Node's util.types predicates in this exact order: isDate, isRegExp, isMap, isSet, isPromise, isArrayBuffer, then isTypedArray.
Return the first matching label ('date', 'regexp', 'map', 'set', 'promise', 'arraybuffer', 'typedarray') or 'other' when none match.
util.types is used instead of instance... | ;
assert.strictEqual(typeof classifyBuiltInValue.doc, 'string');
assert.ok(classifyBuiltInValue.doc.includes('util.types'));
assert.ok(classifyBuiltInValue.doc.includes('isDate'));
assert.ok(classifyBuiltInValue.doc.includes('isTypedArray'));
assert.strictEqual(classifyBuiltInValue(new Date()), 'date');
assert.strict... | for (const term of [
'exact order',
'isRegExp',
'isMap',
'isSet',
'isPromise',
'first matching label',
'instead of instanceof',
'across vm contexts',
'not ArrayBuffer itself'
]) {
assert.ok(classifyBuiltInValue.doc.includes(term), 'doc missing ' + term);
}
assert.strictEqual(classifyBuiltInValue(new... | api_usage |
17 | devbench-api-usage | javascript | const util = require('util');
const assert = require('assert');
class SecretBox {
constructor(value) { this._value = value; }
getValue() { return this._value; }
[util.inspect.custom](depth, options, inspect) {
return 'SecretBox [REDACTED]';
}
}
// Fill in precise API documentation for SecretBox.
// The ex... | `SecretBox stores the original value on _value and returns it unchanged from getValue().
It defines a method keyed by util.inspect.custom, the same symbol as Symbol.for('nodejs.util.inspect.custom'), so util.inspect(instance) uses that hook instead of default property inspection.
The custom inspect hook receives depth,... | ;
assert.strictEqual(typeof SecretBox.doc, 'string');
assert.ok(SecretBox.doc.includes('util.inspect.custom'));
assert.ok(SecretBox.doc.includes("Symbol.for('nodejs.util.inspect.custom')"));
assert.ok(SecretBox.doc.includes('SecretBox [REDACTED]'));
const box = new SecretBox('hidden');
assert.strictEqual(box.getValue... | for (const term of [
'stores the original value on _value',
'returns it unchanged from getValue()',
'uses that hook instead of default property inspection',
'depth, options, and inspect arguments',
'ignores them',
'redacts display output only',
'does not remove or encrypt _value'
]) {
assert.ok(SecretBo... | api_usage |
18 | devbench-api-usage | javascript | const path = require('path');
const assert = require('assert');
function describePosixRelative(from, to) {
const relative = path.posix.relative(from, to);
const segments = relative === '' ? [] : relative.split('/');
const depth = segments.filter(segment => segment === '..').length;
return { relative, segments,... | `Compute the POSIX relative path string with path.posix.relative(from, to), so separators are forward slashes regardless of the host platform.
Split the non-empty relative string on '/' into segments, but use [] when path.posix.relative returns '' for identical paths.
Depth is the count of segments exactly equal to '..... | ;
assert.strictEqual(typeof describePosixRelative.doc, 'string');
assert.ok(describePosixRelative.doc.includes('path.posix.relative(from, to)'));
assert.ok(describePosixRelative.doc.includes("returns '' for identical paths"));
assert.ok(describePosixRelative.doc.includes('forward slashes'));
assert.deepStrictEqual(de... | for (const term of [
'POSIX relative path string',
'regardless of the host platform',
"Split the non-empty relative string on '/'",
'use []',
'count of segments exactly equal to \'..\'',
'lexical path computation only',
'does not access the filesystem',
'process.cwd()'
]) {
assert.ok(describePosixRela... | api_usage |
19 | devbench-api-usage | javascript | const querystring = require('querystring');
const assert = require('assert');
function legacySemiColonQuery(obj) {
return querystring.stringify(obj, ';', ':', {
encodeURIComponent: s => s
});
}
// Fill in precise API documentation for legacySemiColonQuery.
// The executable implementation above is the source ... | `Format obj with Node's legacy querystring.stringify(obj, ';', ':', { encodeURIComponent: s => s }).
The second argument ';' is the pair separator, the third argument ':' is the key/value separator, and the custom encodeURIComponent option is a no-op identity encoder.
Because encoding is disabled, spaces and reserved c... | ;
assert.strictEqual(typeof legacySemiColonQuery.doc, 'string');
assert.ok(legacySemiColonQuery.doc.includes('querystring.stringify'));
assert.ok(legacySemiColonQuery.doc.includes("';'"));
assert.ok(legacySemiColonQuery.doc.includes("':'"));
assert.strictEqual(legacySemiColonQuery({ a: '1', b: 'hello world' }), 'a:1;... | for (const term of [
'legacy querystring.stringify',
'second argument',
'pair separator',
'third argument',
'key/value separator',
'no-op identity encoder',
'encoding is disabled',
'kept literally',
'repeated key:value pairs',
'property iteration order'
]) {
assert.ok(legacySemiColonQuery.doc.incl... | api_usage |
20 | devbench-api-usage | javascript | const assert = require('assert');
function deepStrictReport(actual, expected) {
try {
assert.deepStrictEqual(actual, expected);
return { passes: true, name: null, code: null, message: 'equal' };
} catch (error) {
return { passes: false, name: error.name, code: error.code, message: error.message };
}
... | `Call assert.deepStrictEqual(actual, expected) and return { passes: true, name: null, code: null, message: 'equal' } when it does not throw.
When Node throws an AssertionError, catch it and return passes: false plus error.name, error.code, and error.message instead of rethrowing.
Document Node deepStrictEqual semantics... | ;
assert.strictEqual(typeof deepStrictReport.doc, 'string');
assert.ok(deepStrictReport.doc.includes('assert.deepStrictEqual(actual, expected)'));
assert.ok(deepStrictReport.doc.includes('AssertionError'));
assert.ok(deepStrictReport.doc.includes('Object.is'));
assert.deepStrictEqual(deepStrictReport(NaN, NaN), { pas... | for (const term of [
'does not throw',
'instead of rethrowing',
'primitive comparison is based on Object.is',
'NaN equals NaN',
'-0 differs from +0',
'object prototypes',
'own enumerable properties',
'Map/Set contents',
'error.name, error.code, and error.message'
]) {
assert.ok(deepStrictReport.doc.... | api_usage |
21 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
function encryptAes128Gcm(plaintext, key, iv, aad) {
const cipher = crypto.createCipheriv('aes-128-gcm', key, iv);
cipher.setAAD(aad);
let ciphertext = cipher.update(plaintext, 'utf8', 'hex');
ciphertext += cipher.final('hex');
return { ciph... | `Encrypt plaintext with crypto.createCipheriv('aes-128-gcm', key, iv), where key is a 16-byte AES-128 key and iv is the caller-supplied 12-byte GCM nonce.
Call cipher.setAAD(aad) before update/final so aad is authenticated but not encrypted, then encode ciphertext by cipher.update(plaintext, 'utf8', 'hex') plus cipher.... | ;
assert.strictEqual(typeof encryptAes128Gcm.doc, 'string');
assert.ok(encryptAes128Gcm.doc.includes("crypto.createCipheriv('aes-128-gcm'"));
assert.ok(encryptAes128Gcm.doc.includes('cipher.setAAD(aad)'));
assert.ok(encryptAes128Gcm.doc.includes('cipher.getAuthTag()'));
const key = Buffer.alloc(16, 1);
const iv = Buf... | for (const term of [
'16-byte AES-128 key',
'12-byte GCM nonce',
'before update/final',
'authenticated but not encrypted',
"cipher.update(plaintext, 'utf8', 'hex')",
"cipher.final('hex')",
'After final()',
'16-byte authentication tag',
'32 hex characters',
"iv.toString('hex')"
]) {
assert.ok(encry... | api_usage |
22 | devbench-api-usage | javascript | const { Buffer } = require('buffer');
const assert = require('assert');
function concatToTarget(buffers, targetLength) {
const originalLength = buffers.reduce((sum, buf) => sum + buf.length, 0);
const buffer = Buffer.concat(buffers, targetLength);
return {
buffer,
originalLength,
truncated: targetLen... | `Sum the input Buffer lengths to compute originalLength, then call Buffer.concat(buffers, targetLength) with an explicit totalLength.
Node returns a Buffer whose length is exactly targetLength: if targetLength is less than originalLength, bytes after that length are truncated; if it is greater, extra bytes are zero-fil... | ;
assert.strictEqual(typeof concatToTarget.doc, 'string');
assert.ok(concatToTarget.doc.includes('Buffer.concat(buffers, targetLength)'));
assert.ok(concatToTarget.doc.includes('truncated'));
assert.ok(concatToTarget.doc.includes('zero-filled'));
const exact = concatToTarget([Buffer.from('AB'), Buffer.from('CD')], 4)... | for (const term of [
'explicit totalLength',
'length is exactly targetLength',
'less than originalLength',
'bytes after that length are truncated',
'greater',
'extra bytes are zero-filled with 0x00',
'computed from targetLength compared with originalLength',
'input Buffers themselves are not mutated'
])... | api_usage |
23 | devbench-api-usage | javascript | const { StringDecoder } = require('string_decoder');
const assert = require('assert');
function decodeUtf8Chunks(chunks, encoding = 'utf8') {
const decoder = new StringDecoder(encoding);
let text = '';
let hadIncomplete = false;
for (let i = 0; i < chunks.length; i++) {
const decoded = decoder.write(chunks... | `Create new StringDecoder(encoding) and feed each Buffer chunk through decoder.write(chunk), appending the decoded string output.
StringDecoder preserves incomplete multi-byte UTF-8 sequences across chunk boundaries instead of emitting replacement characters the way independent Buffer.toString('utf8') calls can.
Call d... | ;
assert.strictEqual(typeof decodeUtf8Chunks.doc, 'string');
assert.ok(decodeUtf8Chunks.doc.includes('new StringDecoder(encoding)'));
assert.ok(decodeUtf8Chunks.doc.includes('decoder.write(chunk)'));
assert.ok(decodeUtf8Chunks.doc.includes('decoder.end()'));
const ascii = decodeUtf8Chunks([Buffer.from('Hello'), Buffe... | for (const term of [
'incomplete multi-byte UTF-8 sequences',
'across chunk boundaries',
'instead of emitting replacement characters',
"independent Buffer.toString('utf8') calls",
'flush any buffered bytes',
'chunks.length',
'non-final chunk',
'fewer decoded characters than its byte length'
]) {
asser... | api_usage |
24 | devbench-api-usage | javascript | const { URL, URLSearchParams } = require('url');
const assert = require('assert');
// Build a function that merges query parameters from two URL strings.
// Rules:
// 1. Base URL provides the origin, pathname, and initial params
// 2. Override URL provides additional params to merge
// 3. If a param exists in BOTH, us... | function mergeURLParams(baseUrl, overrideUrl) {
const base = new URL(baseUrl);
const override = new URL(overrideUrl);
const merged = new URLSearchParams();
const overrideKeys = new Set();
for (const [key] of override.searchParams) overrideKeys.add(key);
for (const [key, value] of base.searchPara... | // Basic merge
const r1 = mergeURLParams(
'https://example.com/path?a=1&b=2',
'https://other.com/?b=3&c=4'
);
assert.strictEqual(r1.params.a, '1');
assert.strictEqual(r1.params.b, '3'); // overridden
assert.strictEqual(r1.params.c, '4');
assert.ok(r1.href.startsWith('https://example.com/path'));
// Multi-valu... | // No overlap
const r5 = mergeURLParams(
'https://example.com/?a=1',
'https://x.com/?b=2'
);
assert.strictEqual(r5.params.a, '1');
assert.strictEqual(r5.params.b, '2');
// Empty base params
const r6 = mergeURLParams(
'https://example.com/page',
'https://x.com/?foo=bar'
);
assert.strictEqual(r6.params.f... | api_usage |
25 | devbench-api-usage | javascript | const util = require('util');
const assert = require('assert');
// Write a function that classifies a value into one of these categories
// using util.types functions:
// 'promise', 'generator', 'generatorFunction', 'asyncFunction',
// 'map', 'set', 'date', 'regexp', 'proxy', 'typedArray', 'other'
//
// The functi... | function classifyValue(value) {
if (util.types.isProxy(value)) return 'proxy';
if (util.types.isPromise(value)) return 'promise';
if (util.types.isGeneratorFunction(value)) return 'generatorFunction';
if (util.types.isAsyncFunction(value)) return 'asyncFunction';
if (util.types.isMap(value)) return ... | // Basic type checks
assert.strictEqual(classifyValue(Promise.resolve()), 'promise');
assert.strictEqual(classifyValue(function*() {}), 'generatorFunction');
assert.strictEqual(classifyValue(async function() {}), 'asyncFunction');
assert.strictEqual(classifyValue(new Map()), 'map');
assert.strictEqual(classifyValue(new... | // Proxy wins over underlying type (proxy of a map -> 'proxy')
const proxyMap = new Proxy(new Map(), {});
assert.strictEqual(classifyValue(proxyMap), 'proxy');
// Different TypedArray types
assert.strictEqual(classifyValue(new Float64Array(3)), 'typedArray');
assert.strictEqual(classifyValue(new Int32Array(2)), 'typed... | api_usage |
26 | devbench-api-usage | javascript | const zlib = require('zlib');
const assert = require('assert');
function brotliTextSummary(text, quality = zlib.constants.BROTLI_MAX_QUALITY) {
const input = Buffer.from(text, 'utf8');
const compressed = zlib.brotliCompressSync(input, {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: quality,
[zli... | `Encode text as UTF-8 bytes with Buffer.from(text, 'utf8'), then call zlib.brotliCompressSync(input, { params }) and return the compressed Buffer plus size metadata.
The params object uses computed keys [zlib.constants.BROTLI_PARAM_QUALITY] and [zlib.constants.BROTLI_PARAM_MODE], defaulting quality to zlib.constants.BR... | ;
assert.strictEqual(typeof brotliTextSummary.doc, 'string');
assert.ok(brotliTextSummary.doc.includes('zlib.brotliCompressSync'));
assert.ok(brotliTextSummary.doc.includes('BROTLI_PARAM_QUALITY'));
assert.ok(brotliTextSummary.doc.includes('BROTLI_MODE_TEXT'));
const text = 'The quick brown fox jumps over the lazy do... | for (const term of [
"Buffer.from(text, 'utf8')",
'compressed Buffer',
'size metadata',
'computed keys',
'[zlib.constants.BROTLI_PARAM_QUALITY]',
'[zlib.constants.BROTLI_PARAM_MODE]',
'defaulting quality to zlib.constants.BROTLI_MAX_QUALITY',
'UTF-8 byte length',
'compressed.length / input.length',
... | api_usage |
27 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
// Write a function that generates an array of n cryptographically secure
// random integers in the range [min, max) using crypto.randomInt.
// Also compute basic statistics: { values: number[], min: number, max: number, allInRange: boolean }
// NOTE:... | function generateSecureInts(n, min, max) {
const values = [];
for (let i = 0; i < n; i++) {
values.push(crypto.randomInt(min, max));
}
const actualMin = Math.min(...values);
const actualMax = Math.max(...values);
const allInRange = values.every(v => v >= min && v < max);
return { val... | // Generate 1000 random integers in [0, 10)
const r1 = generateSecureInts(1000, 0, 10);
assert.strictEqual(r1.values.length, 1000);
assert.strictEqual(r1.allInRange, true);
assert.ok(r1.min >= 0);
assert.ok(r1.max <= 9); // max is exclusive, so actual max should be at most 9
assert.ok(r1.max >= 7, 'With 1000 samples, ... | // Negative range [−10, 0)
const r4 = generateSecureInts(200, -10, 0);
assert.strictEqual(r4.allInRange, true);
assert.ok(r4.min >= -10);
assert.ok(r4.max <= -1);
// Large range
const r5 = generateSecureInts(100, 0, 1000000);
assert.strictEqual(r5.allInRange, true);
// Small sample
const r6 = generateSecureInts(1, 0,... | api_usage |
28 | devbench-api-usage | javascript | const { EventEmitter, once } = require('events');
const assert = require('assert');
// Write an async function that waits for a specific event on an emitter,
// but with a timeout implemented via AbortSignal.
//
// Returns: { event: string, args: any[], timedOut: boolean }
//
// If the event fires before timeout: { ev... | async function waitForEvent(emitter, eventName, timeoutMs) {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), timeoutMs);
try {
const args = await once(emitter, eventName, { signal: ac.signal });
clearTimeout(timer);
return { event: eventName, args, timedO... | (async () => {
// Event fires before timeout
const em1 = new EventEmitter();
setTimeout(() => em1.emit('data', 'hello', 42), 10);
const r1 = await waitForEvent(em1, 'data', 1000);
assert.strictEqual(r1.event, 'data');
assert.deepStrictEqual(r1.args, ['hello', 42]);
assert.strictEqual(r1.time... | (async () => {
// Immediate event (0ms delay) still works
const em4 = new EventEmitter();
setImmediate(() => em4.emit('fast', 'zoom'));
const r4 = await waitForEvent(em4, 'fast', 1000);
assert.strictEqual(r4.timedOut, false);
assert.deepStrictEqual(r4.args, ['zoom']);
// Very short timeout ... | api_usage |
29 | devbench-api-usage | javascript | const fs = require('fs');
const os = require('os');
const path = require('path');
const assert = require('assert');
// Write a function that creates a temp directory with proper prefix handling.
// The function should:
// 1. Use fs.mkdtempSync with os.tmpdir() as the base
// 2. The prefix MUST use path.join(os.tmpdir(... | function createTempDir(prefix = 'myapp-') {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
const testFile = path.join(dir, 'test.txt');
fs.writeFileSync(testFile, 'temp file contents');
return {
dir,
testFile,
isTemp: dir.startsWith(os.tmpdir())
};
}
| // Create temp dir and verify
const r1 = createTempDir('unittest-');
assert.ok(fs.existsSync(r1.dir), 'Temp dir should exist');
assert.ok(fs.existsSync(r1.testFile), 'Test file should exist');
assert.strictEqual(r1.isTemp, true, 'Dir should be under tmpdir');
assert.ok(r1.dir.includes('unittest-'), 'Dir should contain ... | // Default prefix
const r3 = createTempDir();
assert.ok(fs.existsSync(r3.dir));
assert.ok(path.basename(r3.dir).startsWith('myapp-'));
assert.strictEqual(r3.isTemp, true);
fs.unlinkSync(r3.testFile);
fs.rmdirSync(r3.dir);
// Empty prefix
const r4 = createTempDir('');
assert.ok(fs.existsSync(r4.dir));
assert.strictEqua... | api_usage |
30 | devbench-api-usage | javascript | const { pathToFileURL, fileURLToPath } = require('url');
const path = require('path');
const assert = require('assert');
// Write a function that demonstrates file URL conversion edge cases.
// Given an array of absolute file paths, return an array of objects:
// { path: string, fileUrl: string, roundTrip: string, r... | function analyzeFilePaths(paths) {
return paths.map(p => {
const fileUrl = pathToFileURL(p).href;
const roundTrip = fileURLToPath(fileUrl);
return {
path: p,
fileUrl,
roundTrip,
roundTripMatch: p === roundTrip
};
});
}
| // Simple path
const r1 = analyzeFilePaths(['/tmp/test.txt']);
assert.strictEqual(r1[0].fileUrl, 'file:///tmp/test.txt');
assert.strictEqual(r1[0].roundTrip, '/tmp/test.txt');
assert.strictEqual(r1[0].roundTripMatch, true);
// Path with spaces (should be percent-encoded in URL)
const r2 = analyzeFilePaths(['/tmp/my fi... | // Path with Unicode characters
const r5 = analyzeFilePaths(['/tmp/日本語.txt']);
assert.strictEqual(r5[0].roundTripMatch, true);
assert.ok(r5[0].fileUrl.startsWith('file:///'));
// Path with percent sign (should be double-encoded)
const r6 = analyzeFilePaths(['/tmp/100%done.txt']);
assert.ok(r6[0].fileUrl.includes('%25'... | api_usage |
31 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
// Custom HMAC library that derives the signing key before use
// Key derivation: HMAC-SHA256(salt, rawKey) -> derivedKey
// Then: HMAC-SHA256(derivedKey, message) -> signature
function deriveKey(rawKey, salt) {
return crypto.createHmac('sha256',... | function signSha512(message, rawKey, salt) {
const dk = deriveKey(rawKey, salt);
return crypto.createHmac('sha512', dk)
.update(message)
.digest('hex');
}
|
// signSha512 uses the same key derivation but HMAC-SHA512 for signing
const s1 = signSha512('hello', 'key', 'salt');
assert.strictEqual(s1.length, 128); // SHA-512 hex = 128 chars
// Same key derivation, different hash -> different signature
const s256 = signSha256('hello', 'key', 'salt');
assert.notStrictEqual(s1, ... |
// Different messages produce different signatures
assert.notStrictEqual(
signSha512('a', 'key', 'salt'),
signSha512('b', 'key', 'salt')
);
// Different keys produce different signatures
assert.notStrictEqual(
signSha512('msg', 'key1', 'salt'),
signSha512('msg', 'key2', 'salt')
);
// Different salts ... | api_usage |
32 | devbench-api-usage | javascript | const assert = require('assert');
// Custom Buffer comparison utilities
// Each function returns { result, metadata } with comparison details
function compareBuffersFull(buf1, buf2) {
const cmp = Buffer.compare(buf1, buf2);
return {
result: cmp,
metadata: {
buf1Length: buf1.length,... | function compareBuffersSlice(buf1, buf2, offset1, offset2, length) {
const slice1 = buf1.subarray(offset1, offset1 + length);
const slice2 = buf2.subarray(offset2, offset2 + length);
const cmp = Buffer.compare(slice1, slice2);
return {
result: cmp,
metadata: {
buf1Length: buf... |
// compareBuffersSlice compares slices of two buffers
const b1 = Buffer.from('xxabcxx');
const b2 = Buffer.from('yyabcyy');
// Compare the 'abc' portion of each
const cs1 = compareBuffersSlice(b1, b2, 2, 2, 3);
assert.strictEqual(cs1.result, 0);
assert.strictEqual(cs1.metadata.equal, true);
assert.strictEqual(cs1.met... |
// Edge case: zero-length comparison is always equal
const ez = compareBuffersSlice(Buffer.from('abc'), Buffer.from('xyz'), 0, 0, 0);
assert.strictEqual(ez.result, 0);
assert.strictEqual(ez.metadata.equal, true);
assert.strictEqual(ez.metadata.sliceLength, 0);
// Same buffer different offsets
const same = Buffer.from... | api_usage |
33 | devbench-api-usage | javascript | const { format, inspect } = require('util');
const assert = require('assert');
// We test precise behavior of util.format specifiers
// %s - String
// %d - Number (integer or float parsed via parseFloat)
// %j - JSON (JSON.stringify)
// %o - Object (util.inspect with showHidden and depth)
// %O - Object (util.inspect ... | // Build a function that formats a log line with mixed specifiers
function formatLogLine(level, code, data, extra) {
// Pattern: "[LEVEL] code=%d data=%j (extra=%s) 100%%"
return format('[%s] code=%d data=%j (extra=%s) 100%%', level, code, data, extra);
}
|
// Test formatLogLine with various inputs
const line1 = formatLogLine('INFO', 200, { ok: true }, 'done');
assert.strictEqual(line1, '[INFO] code=200 data={"ok":true} (extra=done) 100%');
const line2 = formatLogLine('ERROR', '404abc', [1], null);
assert.strictEqual(line2, '[ERROR] code=NaN data=[1] (extra=null) 100%')... |
// Edge cases for format specifiers
// %d with boolean true -> 1
const line4 = formatLogLine('DEBUG', false, {}, 0);
assert.strictEqual(line4, '[DEBUG] code=0 data={} (extra=0) 100%');
// Nested object in %j
const line5 = formatLogLine('INFO', 42, { a: { b: 1 } }, 'x');
assert.strictEqual(line5, '[INFO] code=42 data=... | api_usage |
34 | devbench-api-usage | javascript | const assert = require('assert');
// TextEncoder/TextDecoder behavior tests
// Key behaviors to understand:
// 1. TextDecoder('utf-8', { fatal: true }) throws on invalid sequences
// 2. TextDecoder('utf-8', { ignoreBOM: false }) (default) strips BOM
// 3. TextDecoder('utf-8', { ignoreBOM: true }) preserves BOM
const ... | // Create a function that decodes with configurable error handling and BOM behavior
function safeDecode(uint8arr, options = {}) {
const { fatal = false, keepBOM = false } = options;
const dec = new TextDecoder('utf-8', { fatal, ignoreBOM: keepBOM });
try {
return { text: dec.decode(uint8arr), error:... |
// Non-fatal mode replaces invalid sequences with U+FFFD
const invalid = new Uint8Array([0x48, 0x80, 0x69]); // 'H' + invalid + 'i'
const r1 = safeDecode(invalid);
assert.strictEqual(r1.error, null);
assert.strictEqual(r1.text, 'H�i');
// Fatal mode throws on invalid sequences
const r2 = safeDecode(invalid, { fatal: ... |
// Empty input
const r5 = safeDecode(new Uint8Array([]));
assert.strictEqual(r5.text, '');
assert.strictEqual(r5.error, null);
// Valid UTF-8 multi-byte: e2 9c 93 = checkmark U+2713
const check = new Uint8Array([0xE2, 0x9C, 0x93]);
const r6 = safeDecode(check);
assert.strictEqual(r6.text, '✓');
// Fatal + valid inpu... | api_usage |
35 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
// Hash utility library: each function hashes data and returns
// { hash, algorithm, encoding, inputLength }
function hashHex(algorithm, data) {
const h = crypto.createHash(algorithm).update(data).digest('hex');
return {
hash: h,
... | function hashBase64(algorithm, data) {
const h = crypto.createHash(algorithm).update(data).digest('base64');
return {
hash: h,
algorithm,
encoding: 'base64',
inputLength: Buffer.byteLength(data)
};
}
|
// hashBase64 uses base64 encoding instead of hex
const sha256b64 = hashBase64('sha256', 'hello');
assert.strictEqual(sha256b64.encoding, 'base64');
assert.strictEqual(sha256b64.algorithm, 'sha256');
assert.strictEqual(sha256b64.inputLength, 5);
// Verify the actual hash value
const expected = crypto.createHash('sha2... |
// Empty string
const empty = hashBase64('sha256', '');
assert.strictEqual(empty.inputLength, 0);
assert.strictEqual(empty.hash, crypto.createHash('sha256').update('').digest('base64'));
// UTF-8 multi-byte: inputLength is byte length, not char length
const utf8 = hashBase64('sha256', 'é'); // e-acute = 2 bytes in U... | api_usage |
36 | devbench-api-usage | javascript | const assert = require('assert');
// Number formatting utility using Intl.NumberFormat
// Returns { formatted, parts } where parts is from formatToParts
function formatCurrency(amount, currency, locale) {
const fmt = new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency
});
... | function formatPercent(value, locale, minFrac, maxFrac) {
const fmt = new Intl.NumberFormat(locale, {
style: 'percent',
minimumFractionDigits: minFrac,
maximumFractionDigits: maxFrac
});
const parts = fmt.formatToParts(value);
return {
formatted: fmt.format(value),
... |
// Intl.NumberFormat 'percent' style multiplies the value by 100
// So 0.1234 -> "12.34%"
const p1 = formatPercent(0.1234, 'en-US', 1, 2);
assert.strictEqual(p1.formatted, '12.34%');
assert.ok(p1.parts.some(p => p.type === 'percentSign'));
// With minimumFractionDigits: 0.5 -> "50.0%"
const p2 = formatPercent(0.5, 'e... |
// Negative percentage
const p5 = formatPercent(-0.05, 'en-US', 1, 2);
assert.ok(p5.formatted.includes('-'));
assert.ok(p5.formatted.includes('5.0'));
// Zero
const p6 = formatPercent(0, 'en-US', 2, 2);
assert.strictEqual(p6.formatted, '0.00%');
// Value > 1 means > 100%
const p7 = formatPercent(1.5, 'en-US', 0, 0);... | api_usage |
37 | devbench-api-usage | javascript | const assert = require('assert');
// RegExp pattern library using named capture groups
// Each function returns match groups as a structured object
function parseDate(str) {
const re = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
const m = str.match(re);
if (!m) return null;
return {
year... | function parseDuration(str) {
const re = /^(?<hours>\d+)h(?<minutes>\d+)m(?<seconds>\d+)s$/;
const m = str.match(re);
if (!m) return null;
return {
hours: parseInt(m.groups.hours, 10),
minutes: parseInt(m.groups.minutes, 10),
seconds: parseInt(m.groups.seconds, 10),
total... |
// parseDuration parses "XhYmZs" format using named groups
const dur1 = parseDuration('2h30m45s');
assert.strictEqual(dur1.hours, 2);
assert.strictEqual(dur1.minutes, 30);
assert.strictEqual(dur1.seconds, 45);
assert.strictEqual(dur1.totalSeconds, 2 * 3600 + 30 * 60 + 45);
assert.strictEqual(dur1.raw, '2h30m45s');
co... |
// Large values
const dur3 = parseDuration('100h59m59s');
assert.strictEqual(dur3.hours, 100);
assert.strictEqual(dur3.totalSeconds, 100 * 3600 + 59 * 60 + 59);
// Single digits
const dur4 = parseDuration('1h2m3s');
assert.strictEqual(dur4.hours, 1);
assert.strictEqual(dur4.minutes, 2);
assert.strictEqual(dur4.second... | api_usage |
38 | devbench-api-usage | javascript | const assert = require('assert');
// Locale-aware string sorting utilities using Intl.Collator
// Each function returns { sorted, locale, options }
function sortCaseSensitive(arr, locale) {
const collator = new Intl.Collator(locale, { sensitivity: 'case' });
const sorted = [...arr].sort(collator.compare);
... | function sortNatural(arr, locale) {
const collator = new Intl.Collator(locale, { numeric: true, sensitivity: 'base' });
const sorted = [...arr].sort(collator.compare);
return { sorted, locale, options: { numeric: true, sensitivity: 'base' } };
}
|
// sortNatural uses numeric: true for natural number ordering
// "file2" comes before "file10" (unlike lexicographic sort)
const ns1 = sortNatural(['file10', 'file2', 'file1', 'file20'], 'en');
assert.deepStrictEqual(ns1.sorted, ['file1', 'file2', 'file10', 'file20']);
assert.strictEqual(ns1.locale, 'en');
assert.stri... |
// Pure numeric strings
const ns4 = sortNatural(['100', '20', '3', '1'], 'en');
assert.deepStrictEqual(ns4.sorted, ['1', '3', '20', '100']);
// Single element
const ns5 = sortNatural(['only'], 'en');
assert.deepStrictEqual(ns5.sorted, ['only']);
// Empty array
const ns6 = sortNatural([], 'en');
assert.deepStrictEqua... | api_usage |
39 | devbench-api-usage | javascript | const crypto = require('crypto');
const assert = require('assert');
// Token generation utility library
// Each generator returns { token, encoding, byteLength }
function generateHexToken(byteLength) {
const buf = crypto.randomBytes(byteLength);
return {
token: buf.toString('hex'),
encoding: '... | function generateBase64Token(byteLength) {
const buf = crypto.randomBytes(byteLength);
return {
token: buf.toString('base64'),
encoding: 'base64',
byteLength
};
}
|
// Base64 token: each 3 bytes -> 4 chars, with padding
const bt = generateBase64Token(16);
assert.strictEqual(bt.encoding, 'base64');
assert.strictEqual(bt.byteLength, 16);
// 16 bytes = ceil(16/3)*4 = 24 base64 chars (with padding)
assert.strictEqual(bt.token.length, 24);
assert.ok(/^[A-Za-z0-9+/]+=*$/.test(bt.token)... |
// Various byte lengths
const bt3 = generateBase64Token(1);
assert.strictEqual(bt3.token.length, 4); // 1 byte -> 4 chars (2 padding)
assert.strictEqual(bt3.byteLength, 1);
const bt4 = generateBase64Token(3);
assert.strictEqual(bt4.token.length, 4); // 3 bytes -> 4 chars (no padding)
const bt5 = generateBase64Toke... | api_usage |
40 | devbench-api-usage | javascript | const assert = require('assert');
// URL parsing utility using the WHATWG URL API
// Returns structured info about a URL
function parseUrlBasic(urlStr) {
const url = new URL(urlStr);
return {
protocol: url.protocol, // includes trailing ':'
hostname: url.hostname,
port: url.port, ... | function parseUrlQuery(urlStr) {
const url = new URL(urlStr);
const params = {};
url.searchParams.forEach((value, key) => {
if (params[key]) {
if (!Array.isArray(params[key])) params[key] = [params[key]];
params[key].push(value);
} else {
params[key] = val... |
// parseUrlQuery extracts query parameters into a params object
const q1 = parseUrlQuery('https://api.example.com/search?q=hello&lang=en');
assert.strictEqual(q1.protocol, 'https:');
assert.strictEqual(q1.hostname, 'api.example.com');
assert.strictEqual(q1.pathname, '/search');
assert.strictEqual(q1.params.q, 'hello')... |
// URL-encoded values are decoded
const q4 = parseUrlQuery('https://x.com/?msg=hello%20world&x=%26');
assert.strictEqual(q4.params.msg, 'hello world');
assert.strictEqual(q4.params.x, '&');
// Single param, no duplicates
const q5 = parseUrlQuery('https://x.com/?key=value');
assert.strictEqual(q5.params.key, 'value');... | api_usage |
41 | devbench-api-usage | javascript | // Clone an object containing an ArrayBuffer, transferring ownership
// After transfer, the ORIGINAL ArrayBuffer becomes detached (byteLength === 0)
function cloneWithTransfer(obj, bufferKey) {
| const buffer = obj[bufferKey];
const cloned = structuredClone(obj, { transfer: [buffer] });
return { cloned, originalDetached: obj[bufferKey].byteLength === 0 };
| }
const assert = require('assert');
const buf = new ArrayBuffer(16);
const view = new Uint8Array(buf);
view[0] = 42;
view[1] = 99;
const result = cloneWithTransfer({ data: buf, label: 'test' }, 'data');
// The cloned object has the buffer with the data intact
const clonedView = new Uint8Array(result.cloned.data);
as... | // Transfer with a fresh buffer
const buf2 = new ArrayBuffer(8);
new Uint8Array(buf2).set([1, 2, 3, 4, 5, 6, 7, 8]);
const r2 = cloneWithTransfer({ x: buf2 }, 'x');
assert.strictEqual(r2.originalDetached, true);
assert.strictEqual(buf2.byteLength, 0);
assert.strictEqual(r2.cloned.x.byteLength, 8);
const v2 = new Uint8A... | api_usage |
42 | devbench-api-usage | javascript | // A cache that holds WeakRefs to objects and recreates them on demand.
// The factory function is called ONLY when the WeakRef is dead (deref returns undefined).
// Must track how many times the factory was called via `createCount`.
class WeakCache {
constructor(factory) {
this._factory = factory;
... | get(key) {
const ref = this._refs.get(key);
let obj = ref ? ref.deref() : undefined;
if (obj === undefined) {
obj = this._factory(key);
this._refs.set(key, new WeakRef(obj));
this.createCount++;
}
return obj;
}
| has(key) {
const ref = this._refs.get(key);
return ref ? ref.deref() !== undefined : false;
}
delete(key) {
this._refs.delete(key);
}
}
const assert = require('assert');
const cache = new WeakCache((key) => ({ id: key, ts: Date.now() }));
// First get creates the object
const... | // Delete removes the ref, next get recreates
const cache2 = new WeakCache((k) => ({ val: k.toUpperCase() }));
const x = cache2.get('hello');
assert.strictEqual(x.val, 'HELLO');
assert.strictEqual(cache2.createCount, 1);
cache2.delete('hello');
assert.strictEqual(cache2.has('hello'), false);
const y = cache2.get('hel... | api_usage |
43 | devbench-api-usage | javascript | // Run an async task with a timeout. If the task doesn't finish in time,
// abort it with a specific reason. The function must:
// 1. Create an AbortController
// 2. Set up a timeout that calls controller.abort(reason) with reason = 'TIMEOUT'
// 3. Pass the signal to the task function
// 4. Return { result, aborted, re... | const controller = new AbortController();
const timer = setTimeout(() => controller.abort('TIMEOUT'), timeoutMs);
try {
const result = await taskFn(controller.signal);
return { result, aborted: false, reason: null };
} catch (e) {
if (controller.signal.aborted) {
retu... | }
const assert = require('assert');
async function testTimeout() {
// Task that completes quickly
const fast = await withTimeout(async (signal) => {
return 'done';
}, 1000);
assert.deepStrictEqual(fast, { result: 'done', aborted: false, reason: null });
// Task that takes too long and get... | async function testAssertions() {
// Task that throws a non-abort error should re-throw
try {
await withTimeout(async (signal) => {
throw new Error('task-error');
}, 1000);
assert.fail('should have thrown');
} catch (e) {
assert.strictEqual(e.message, 'task-error'... | api_usage |
44 | devbench-api-usage | javascript | // Implement an atomic counter using SharedArrayBuffer and Atomics.
// The counter uses index 0 of a shared Int32Array for the count.
// increment() must use Atomics.add and return the OLD value (before increment).
// get() must use Atomics.load.
// compareAndSwap(expected, desired) must use Atomics.compareExchange
// ... | increment() {
return Atomics.add(this._view, 0, 1);
}
get() {
return Atomics.load(this._view, 0);
}
compareAndSwap(expected, desired) {
return Atomics.compareExchange(this._view, 0, expected, desired) === expected;
}
| }
const assert = require('assert');
const counter = new AtomicCounter(0);
// increment returns OLD value
assert.strictEqual(counter.increment(), 0);
assert.strictEqual(counter.increment(), 1);
assert.strictEqual(counter.increment(), 2);
assert.strictEqual(counter.get(), 3);
// compareAndSwap
assert.strictEqual(coun... | // Multiple increments
const c = new AtomicCounter(0);
const oldVals = [];
for (let i = 0; i < 10; i++) {
oldVals.push(c.increment());
}
assert.deepStrictEqual(oldVals, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
assert.strictEqual(c.get(), 10);
// compareAndSwap chain
assert.strictEqual(c.compareAndSwap(10, 50), true);
asse... | api_usage |
45 | devbench-api-usage | javascript | // Create an array from a range [0, length), where each element is
// transformed by multiplying by `this.multiplier` using Array.from's
// mapFn and thisArg parameters.
// IMPORTANT: Must use Array.from(arrayLike, mapFn, thisArg) — the 3-arg form.
// Arrow functions do NOT respect thisArg, so mapFn must be a regular f... | const ctx = { multiplier };
return Array.from({ length }, function(_, i) { return i * this.multiplier; }, ctx);
| }
const assert = require('assert');
assert.deepStrictEqual(makeScaledRange(5, 2), [0, 2, 4, 6, 8]);
assert.deepStrictEqual(makeScaledRange(4, 10), [0, 10, 20, 30]);
assert.deepStrictEqual(makeScaledRange(3, 0), [0, 0, 0]);
assert.deepStrictEqual(makeScaledRange(0, 5), []);
assert.deepStrictEqual(makeScaledRange(1, 7)... | // Negative multiplier — start from index 1 to avoid -0 issue (0 * -3 === -0)
const neg = makeScaledRange(4, -3);
assert.strictEqual(neg.length, 4);
assert.strictEqual(neg[1], -3);
assert.strictEqual(neg[2], -6);
assert.strictEqual(neg[3], -9);
// Fractional multiplier
const r = makeScaledRange(3, 0.5);
assert.strictE... | api_usage |
46 | devbench-api-usage | javascript | // Create an object with:
// - 'name': a normal writable, enumerable, configurable data property
// - '_accessCount': a non-enumerable, writable data property starting at 0
// - 'greeting': a non-enumerable GETTER that increments _accessCount each time
// it's accessed, and returns 'Hello, <name>!'
// - '... | Object.defineProperties(obj, {
name: { value: name, writable: true, enumerable: true, configurable: true },
_accessCount: { value: 0, writable: true, enumerable: false, configurable: true },
greeting: { get() { this._accessCount++; return 'Hello, ' + this.name + '!'; }, enumerable: false, co... | }
const assert = require('assert');
const p = createTrackedPerson('Alice');
// name is enumerable
assert.deepStrictEqual(Object.keys(p), ['name']);
assert.strictEqual(p.name, 'Alice');
// greeting is a getter, increments access count
assert.strictEqual(p.greeting, 'Hello, Alice!');
assert.strictEqual(p.accessCount,... | const p2 = createTrackedPerson('Zoe');
// Access count starts at 0
assert.strictEqual(p2.accessCount, 0);
// Multiple accesses
for (let i = 0; i < 5; i++) p2.greeting;
assert.strictEqual(p2.accessCount, 5);
// Properties exist on the object (not undefined)
assert.notStrictEqual(Object.getOwnPropertyDescriptor(p2, 'gr... | api_usage |
47 | devbench-api-usage | javascript | // BaseLogger has a log() method. TimestampLogger has a logWithTime() method.
// Use Reflect.construct to create an object that:
// - Is constructed by BaseLogger (runs BaseLogger constructor)
// - But has TimestampLogger.prototype as its prototype (instanceof TimestampLogger)
// This means the object has BaseLogger's ... | return Reflect.construct(BaseLogger, [prefix], TimestampLogger);
| }
const assert = require('assert');
const logger = createHybridLogger('APP');
// Has BaseLogger's constructor behavior (prefix and messages initialized)
assert.strictEqual(logger.prefix, 'APP');
assert.deepStrictEqual(logger.messages, []);
// Is instanceof TimestampLogger (not BaseLogger) because new.target is Time... | // Different prefix
const l2 = createHybridLogger('SYS');
assert.strictEqual(l2.prefix, 'SYS');
assert.strictEqual(l2 instanceof TimestampLogger, true);
assert.strictEqual(l2 instanceof BaseLogger, false);
// Prototype chain
assert.strictEqual(Object.getPrototypeOf(l2), TimestampLogger.prototype);
// logWithTime mess... | api_usage |
48 | devbench-api-usage | javascript | // Create an Array subclass where:
// - The constructor accepts elements and sets a 'tag' property
// - slice, map, filter return PLAIN Arrays (not TaggedArray instances)
// by using Symbol.species = Array
// - A custom toTagged() method returns '[tag]: el1, el2, ...'
class TaggedArray extends Array {
| constructor(tag, ...items) {
super(...items);
this.tag = tag;
}
static get [Symbol.species]() {
return Array;
}
toTagged() {
return '[' + this.tag + ']: ' + this.join(', ');
}
| }
const assert = require('assert');
const ta = new TaggedArray('nums', 1, 2, 3, 4, 5);
assert.strictEqual(ta.length, 5);
assert.strictEqual(ta.tag, 'nums');
assert.strictEqual(ta instanceof TaggedArray, true);
assert.strictEqual(ta instanceof Array, true);
// toTagged format
assert.strictEqual(ta.toTagged(), '[nums]... | // Empty TaggedArray
const empty = new TaggedArray('e');
assert.strictEqual(empty.length, 0);
assert.strictEqual(empty.tag, 'e');
assert.strictEqual(empty.toTagged(), '[e]: ');
// Slice of empty
const es = empty.slice();
assert.strictEqual(es instanceof TaggedArray, false);
assert.deepStrictEqual(es, []);
// Concat w... | api_usage |
49 | devbench-api-usage | javascript | // Capture a structured stack trace at the point where this function is called.
// Must use Error.captureStackTrace and Error.prepareStackTrace to get an array
// of CallSite objects, then map them to { function, file, line } objects.
// The constructorOpt parameter hides frames above the given function.
//
// Returns ... | const orig = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const obj = {};
Error.captureStackTrace(obj, constructorOpt || getStructuredStack);
const raw = obj.stack;
Error.prepareStackTrace = orig;
return raw.map(s => ({
function: s.getFunctionName() || '<an... | }
const assert = require('assert');
// Call from a named function
function outerFunction() {
function innerFunction() {
return getStructuredStack();
}
return innerFunction();
}
const stack = outerFunction();
// stack is an array of objects
assert.ok(Array.isArray(stack));
assert.ok(stack.length ... | // Test with constructorOpt to hide frames
function wrapper() {
function target() {
return getStructuredStack(wrapper);
}
return target();
}
const s2 = wrapper();
// wrapper and everything above it should be hidden
// So the top frame should NOT be 'target' or 'wrapper'
const fnNames = s2.map(f => ... | api_usage |
50 | devbench-api-usage | javascript | const { performance, PerformanceObserver } = require('perf_hooks');
// Measure the execution time of a synchronous function using Performance marks.
// Must use performance.mark() and performance.measure() (NOT Date.now()).
// Returns { result, durationMs, markStart, markEnd, measureName }
function measureSync(name, f... | const markStart = name + '-start';
const markEnd = name + '-end';
const measureName = name + '-duration';
performance.mark(markStart);
const result = fn();
performance.mark(markEnd);
performance.measure(measureName, markStart, markEnd);
const entry = performance.getEntriesByName(measureN... | }
const assert = require('assert');
// Measure a simple computation
const r = measureSync('test1', () => {
let sum = 0;
for (let i = 0; i < 100000; i++) sum += i;
return sum;
});
assert.strictEqual(r.result, 4999950000);
assert.strictEqual(typeof r.durationMs, 'number');
assert.ok(r.durationMs >= 0, 'Dur... | // Measure a fast no-op
const r2 = measureSync('fast', () => 42);
assert.strictEqual(r2.result, 42);
assert.strictEqual(typeof r2.durationMs, 'number');
assert.ok(r2.durationMs >= 0);
assert.strictEqual(r2.markStart, 'fast-start');
// Measure something that returns a string
const r3 = measureSync('str', () => 'hello'.... | api_usage |
1 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class Subscription {
static VALID_TRANSITIONS = {
pending: ['active'],
active: ['paused', 'cancelled'],
paused: ['active', 'cancelled'],
cancelled: []
};
constructor(userId, plan) {
this.userId = userId;
this.plan = plan;
... | activate(ts) {
this._transition('active', ts);
this.activatedAt = ts;
}
|
pause(ts) {
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.auditLog[0], {... |
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) {
assert.ok(e.message.includes('C... | code_purpose_understanding |
2 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class LoanAccount {
constructor(loanId) {
this.loanId = loanId;
this.feesDue = 0;
this.interestDue = 0;
this.principalDue = 0;
this.unapplied = 0;
this.auditLog = [];
this._idempotencyKeys = new Set();
}
addCharges(f... | applyPayment(paymentId, amount) {
if (this._idempotencyKeys.has(paymentId)) {
return this.auditLog.find(e => e.paymentId === paymentId).applied;
}
this._idempotencyKeys.add(paymentId);
let remaining = amount;
const feePart = Math.min(remaining, this.feesDue);
... |
}
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); // unchanged
// Second payment: all goes to principal since fees/inter... | code_purpose_understanding |
3 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class InsurancePlan {
constructor(copay, deductible, coinsurancePct, outOfPocketMax) {
this.copay = copay; // fixed copay per claim
this.deductible = deductible; // annual deductible
this.coinsurancePct = coinsurancePct; // memb... | adjudicate(claimId, billedAmount) {
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);
if (this.oopAccumulator >= this.... |
}
// Plan: $30 copay, $500 deductible, 20% coinsurance, $2000 OOP max
const plan = new InsurancePlan(30, 500, 0.2, 2000);
// Claim 1: $1000 billed
// copay=30, remaining=970, deductible=500 (met 0→500), remaining=470, coinsurance=0.2*470=94
// memberPay=30+500+94=624, oopAcc=624
const c1 = plan.adjudicate('C1', 1000... |
// Claim 2: $2000 billed
// copay=30, remaining=1970, deductible already met, coinsurance=0.2*1970=394
// memberPay=30+0+394=424, oopAcc=624+424=1048
const c2 = plan.adjudicate('C2', 2000);
assert.strictEqual(c2.memberPay, 424);
assert.strictEqual(c2.planPay, 1576);
assert.strictEqual(plan.oopAccumulator, 1048);
// C... | code_purpose_understanding |
4 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class EscrowAccount {
constructor(totalAmount, holdbackPct) {
this.totalAmount = totalAmount;
this.holdbackPct = holdbackPct; // e.g. 0.1 means 10% retained
this.released = 0;
this.holdback = 0;
this.defects = new Set(); // active ... | releaseMilestone(milestoneId) {
if (this._processedIds.has(milestoneId)) {
const cached = this.log.find(e => e.milestoneId === milestoneId);
return { released: cached.net, blocked: false };
}
if (!this.milestones[milestoneId]) {
return { released: 0, block... |
}
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, ... |
// 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); // unchanged
// Resolve defect, now M2 releases
escrow.resolveDefect('D1');
const r2b = esc... | code_purpose_understanding |
5 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class UsageBilling {
constructor(ratePerUnit, minimumCommit) {
this.ratePerUnit = ratePerUnit;
this.minimumCommit = minimumCommit; // minimum charge per period
this.credits = []; // { id, amount } — applied FIFO
this.invoices = {}... | closePeriod(periodId, units) {
if (this.invoices[periodId]) {
return this.invoices[periodId];
}
const gross = Math.max(units * this.ratePerUnit, this.minimumCommit);
let remaining = gross;
const creditsUsed = [];
while (remaining > 0 && this.credits.length... |
}
const billing = new UsageBilling(0.05, 100); // $0.05/unit, $100 minimum
billing.addCredit('CR1', 30);
billing.addCredit('CR2', 50);
// Period 1: 3000 units => gross=max(150, 100)=150, credits: CR1 used 30, CR2 used 50 => net=70
const inv1 = billing.closePeriod('JAN', 3000);
assert.strictEqual(inv1.gross, 150);
a... |
// Period 2: low usage, minimum commit kicks in
// 500 units => gross=max(25, 100)=100, no credits left => net=100
const inv2 = billing.closePeriod('FEB', 500);
assert.strictEqual(inv2.gross, 100);
assert.strictEqual(inv2.net, 100);
assert.strictEqual(billing.totalBilled, 170);
// Add a large credit and test partial ... | code_purpose_understanding |
6 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class LeaveTracker {
constructor(annualBalance) {
this.balance = annualBalance; // in half-day units (e.g., 40 = 20 full days)
this.requests = {}; // requestId -> request object
this.blackoutDates = new Set(); // dates that cannot be taken off... | requestLeave(requestId, dates, halfDay) {
if (this.requests[requestId]) {
const cached = this.requests[requestId];
return cached.status === 'approved'
? { approved: true, cost: cached.cost, remainingBalance: this.balance }
: cached.result;
}
... |
}
const lt = new LeaveTracker(40); // 20 full days = 40 half-day units
lt.addBlackout('2024-12-25');
lt.addBlackout('2024-01-01');
// Full day request: 3 dates = 6 half-day units
const r1 = lt.requestLeave('R1', ['2024-03-01', '2024-03-02', '2024-03-03'], false);
assert.strictEqual(r1.approved, true);
assert.strictE... |
// Half-day request: 2 dates = 2 half-day units
const r2 = lt.requestLeave('R2', ['2024-04-01', '2024-04-02'], true);
assert.strictEqual(r2.approved, true);
assert.strictEqual(r2.cost, 2);
assert.strictEqual(r2.remainingBalance, 32);
// Blackout date
const r3 = lt.requestLeave('R3', ['2024-06-01', '2024-12-25', '2024... | code_purpose_understanding |
7 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class IncidentTracker {
static VALID_TRANSITIONS = {
open: ['investigating', 'resolved'],
investigating: ['paused', 'resolved'],
paused: ['investigating'],
resolved: []
};
constructor(slaLimitMs) {
this.slaLimitMs = slaLimitMs;
... | transition(incidentId, newState, ts) {
const inc = this.incidents[incidentId];
const allowed = IncidentTracker.VALID_TRANSITIONS[inc.state];
if (!allowed || !allowed.includes(newState)) {
throw new Error(`Cannot transition from ${inc.state} to ${newState}`);
}
con... |
}
const tracker = new IncidentTracker(3600000); // 1 hour SLA
tracker.open('INC1', 0);
const t1 = tracker.transition('INC1', 'investigating', 1000);
assert.strictEqual(t1.state, 'investigating');
assert.strictEqual(t1.activeMs, 1000);
assert.strictEqual(t1.breached, false);
// Pause for 30 minutes
const t2 = tracker... |
// Resume after 30 min pause (at ts=2400000, paused from 600000 to 2400000 = 1800000ms paused)
const t3 = tracker.transition('INC1', 'investigating', 2400000);
// activeMs = 2400000 - 0 - 1800000 = 600000
assert.strictEqual(t3.activeMs, 600000);
assert.strictEqual(t3.breached, false);
// Resolve at ts=4000000
// acti... | code_purpose_understanding |
8 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class Warehouse {
constructor() {
this.stock = {}; // sku -> available quantity
this.reserved = {}; // orderId -> [{ sku, qty }]
this.shipped = new Set();
this.auditLog = [];
}
addStock(sku, qty) {
this.stock[sku] = (this... | reserveOrder(orderId, items) {
if (this.reserved[orderId]) {
return { success: true, alreadyReserved: true };
}
for (const item of items) {
const avail = this.stock[item.sku] || 0;
if (avail < item.qty) {
return { success: false, failedSku:... |
shipOrder(orderId) {
if (this.shipped.has(orderId)) {
return { success: true, alreadyShipped: true };
}
if (!this.reserved[orderId]) {
return { success: false, reason: 'not_reserved' };
}
this.shipped.add(orderId);
delete this.reserved[orderI... |
// Idempotency
const r1dup = wh.reserveOrder('ORD1', [{ sku: 'WIDGET', qty: 30 }, { sku: 'GADGET', qty: 10 }]);
assert.strictEqual(r1dup.success, true);
assert.strictEqual(r1dup.alreadyReserved, true);
assert.strictEqual(wh.stock['WIDGET'], 70); // unchanged
// Insufficient stock - atomic: neither deducted
const r2 ... | code_purpose_understanding |
9 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class InventoryManager {
constructor() {
this.batches = []; // { batchId, sku, qty, expiry (ISO date string) }
this.picks = {}; // pickId -> { items: [{ batchId, qty }], sku, totalQty }
}
addBatch(batchId, sku, qty, expiry) {
this.batches.push(... | pick(pickId, sku, requestedQty, currentDate) {
if (this.picks[pickId]) {
return { success: true, items: this.picks[pickId].items };
}
const eligible = this.batches
.filter(b => b.sku === sku && b.qty > 0 && b.expiry > currentDate)
.sort((a, b) => a.expiry ... |
}
const inv = new InventoryManager();
inv.addBatch('B1', 'MILK', 20, '2024-03-10');
inv.addBatch('B2', 'MILK', 30, '2024-03-05'); // expires sooner
inv.addBatch('B3', 'MILK', 15, '2024-03-15');
inv.addBatch('B4', 'MILK', 10, '2024-02-28'); // already expired
// Pick 40 units of MILK on 2024-03-01
// Eligible (not ... |
// Pick more than available: should fail with rollback
// Available: B1=10, B3=15 = 25 total
const p2 = inv.pick('P2', 'MILK', 30, '2024-03-01');
assert.strictEqual(p2.success, false);
assert.strictEqual(p2.reason, 'insufficient_stock');
assert.strictEqual(p2.available, 25);
// Verify no deduction happened (rollback)
... | code_purpose_understanding |
10 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class PharmacySystem {
constructor(tooSoonPct) {
this.tooSoonPct = tooSoonPct; // e.g., 0.75 means refill allowed when 75% of supply elapsed
this.prescriptions = {}; // rxId -> { drug, daySupply, controlled, fills: [{ fillId, date, type }] }
this._fil... | fill(fillId, rxId, date) {
if (this._fillIds.has(fillId)) {
return { dispensed: false, reason: 'duplicate_fill' };
}
if (!this.prescriptions[rxId]) {
return { dispensed: false, reason: 'unknown_rx' };
}
const rx = this.prescriptions[rxId];
let ... |
}
const pharm = new PharmacySystem(0.75); // too-soon at 75% of supply
pharm.registerRx('RX1', 'Lisinopril', 30, false); // non-controlled, 30-day
pharm.registerRx('RX2', 'Oxycodone', 30, true); // controlled, 30-day
// First fills always allowed
const f1 = pharm.fill('F1', 'RX1', 0);
assert.strictEqual(f1.di... |
// Too-soon threshold for 30-day supply at 75% = floor(22.5) = 22 days
// Non-controlled at day 20 (< 22): early_refill (allowed but flagged)
const f3 = pharm.fill('F3', 'RX1', 20);
assert.strictEqual(f3.dispensed, true);
assert.strictEqual(f3.type, 'early_refill');
assert.strictEqual(f3.fillNumber, 2);
// Controlled... | code_purpose_understanding |
11 | devbench-code-purpose-understanding | javascript | class CouponSystem {
constructor() {
this.coupons = {}; // couponCode -> { discount, minOrder, maxDiscount, singleUse }
this.used = {}; // couponCode -> Set of userIds who used it
this.audit = []; // { action, couponCode, userId, orderTotal, discountApplied, ts }
}
... | redeemCoupon(code, userId, orderTotal, ts) {
const coupon = this.coupons[code];
if (!coupon) {
this._logAudit('INVALID_CODE', code, userId, orderTotal, 0, ts);
return { success: false, reason: 'invalid_code', discount: 0 };
}
if (coupon.singleUse && this.used[... |
}
const assert = require('assert');
const cs = new CouponSystem();
cs.registerCoupon('SAVE20', 0.20, 50, 30, true);
// Valid redemption: 20% of 100 = 20, under cap of 30
const r1 = cs.redeemCoupon('SAVE20', 'user1', 100, 1000);
assert.strictEqual(r1.success, true);
assert.strictEqual(r1.discount, 20);
// Single-us... | // Hidden assertions
const cs2 = new CouponSystem();
cs2.registerCoupon('FREE', 1.0, 0, Infinity, false);
// 100% discount, no cap, not single-use
const h1 = cs2.redeemCoupon('FREE', 'u1', 50, 100);
assert.strictEqual(h1.success, true);
assert.strictEqual(h1.discount, 50);
// Same user can reuse (not single-use)
cons... | code_purpose_understanding |
12 | devbench-code-purpose-understanding | javascript | class LoanAccount {
constructor(principal, annualRate, earlyPayoffPenaltyRate = 0.02) {
this.principal = principal;
this.monthlyRate = annualRate / 12;
this.earlyPayoffPenaltyRate = earlyPayoffPenaltyRate;
this.balance = principal;
this.ytdInterest = 0;
this.ytdPrinci... | makePayment(month, amount) {
if (this.closed) {
return { success: false, reason: 'loan_closed' };
}
const interest = this._roundCents(this.balance * this.monthlyRate);
let penalty = 0;
let principalPaid;
if (amount >= this.balance + interest) {
... |
}
const assert = require('assert');
const loan = new LoanAccount(10000, 0.06, 0.02); // 6% annual, 2% early payoff penalty
// Regular payment: interest first, remainder to principal
const p1 = loan.makePayment(1, 500);
assert.strictEqual(p1.success, true);
assert.strictEqual(p1.interest, 50); // 10000 * 0.... | // Hidden assertions
// Early payoff triggers penalty
const loan2 = new LoanAccount(1000, 0.12, 0.03); // 12% annual, 3% penalty
// Regular payment first
loan2.makePayment(1, 200);
// balance after: 1000*0.01=10 interest, 190 principal, balance=810
const earlyPayoff = loan2.makePayment(2, 2000); // more than enough t... | code_purpose_understanding |
13 | devbench-code-purpose-understanding | javascript | class HotelBooking {
constructor(totalRooms) {
this.totalRooms = totalRooms;
this.confirmed = new Map(); // guestId -> { roomNumber, ts }
this.waitlist = []; // [{ guestId, ts }]
this.nextRoom = 1;
this.log = []; // { action, guestId, roomNumber, ... | book(guestId, ts) {
// Idempotent: if already confirmed, return existing booking
if (this.confirmed.has(guestId)) {
return { status: 'already_confirmed', roomNumber: this.confirmed.get(guestId).roomNumber };
}
// Check if already on waitlist
if (this.waitlist.some... |
}
const assert = require('assert');
const hotel = new HotelBooking(2);
// Book first two guests
const b1 = hotel.book('alice', 100);
assert.strictEqual(b1.status, 'confirmed');
assert.strictEqual(b1.roomNumber, 1);
const b2 = hotel.book('bob', 101);
assert.strictEqual(b2.status, 'confirmed');
assert.strictEqual(b2... | // Hidden assertions
const hotel2 = new HotelBooking(1);
// One room hotel
const h1 = hotel2.book('x', 200);
assert.strictEqual(h1.status, 'confirmed');
// Waitlist two guests
hotel2.book('y', 201);
hotel2.book('z', 202);
assert.strictEqual(hotel2.waitlist.length, 2);
// Re-waitlisting same guest is idempotent
const... | code_purpose_understanding |
14 | devbench-code-purpose-understanding | javascript | class Auction {
constructor(startingPrice, minIncrement, endTime, extensionWindow = 0) {
this.currentPrice = startingPrice;
this.minIncrement = minIncrement;
this.endTime = endTime;
this.extensionWindow = extensionWindow; // extend deadline if bid within this window
this.high... | placeBid(bidder, maxAmount, ts) {
if (this.closed || ts > this.endTime) {
this.closed = true;
return { success: false, reason: 'auction_ended' };
}
if (maxAmount < this.currentPrice + this.minIncrement && bidder !== this.highBidder) {
return { success: fal... |
}
const assert = require('assert');
const auction = new Auction(100, 10, 1000, 60);
// First bid: proxy max 200, price starts at 100+10=110 (but no competitor, so price = startingPrice + increment)
// Actually first bidder: no competition, price = starting + increment = 110
const b1 = auction.placeBid('alice', 200,... | // Hidden assertions
// Alice can't bid below current price + increment
const b4 = auction.placeBid('alice', 215, 800);
assert.strictEqual(b4.success, false);
assert.strictEqual(b4.reason, 'below_minimum');
// Carol raises her own proxy max (price doesn't change)
const b5 = auction.placeBid('carol', 300, 800);
assert.... | code_purpose_understanding |
15 | devbench-code-purpose-understanding | javascript | class PayrollProcessor {
constructor(brackets, preTaxDeductionRate = 0) {
// brackets: [ { upTo, rate }, ... ] sorted ascending by upTo
// e.g. [{ upTo: 1000, rate: 0.10 }, { upTo: 3000, rate: 0.20 }, { upTo: Infinity, rate: 0.30 }]
this.brackets = brackets;
this.preTaxDeductionRate ... | processPaycheck(grossPay, month) {
const preTaxDeduction = Math.round(grossPay * this.preTaxDeductionRate * 100) / 100;
const taxableIncome = grossPay - preTaxDeduction;
const tax = this._calcProgressiveTax(taxableIncome);
const netPay = Math.round((taxableIncome - tax) * 100) / 100;... |
}
const assert = require('assert');
const pp = new PayrollProcessor([
{ upTo: 1000, rate: 0.10 },
{ upTo: 3000, rate: 0.20 },
{ upTo: Infinity, rate: 0.30 }
], 0.05); // 5% pre-tax deduction (e.g., 401k)
// Gross 4000: pre-tax deduction = 200, taxable = 3800
// Tax: 1000*0.10 + 2000*0.20 + 800*0.30 = 10... | // Hidden assertions
// Zero gross
const pp2 = new PayrollProcessor([
{ upTo: 500, rate: 0.05 },
{ upTo: Infinity, rate: 0.15 }
], 0.10);
const s0 = pp2.processPaycheck(0, 'Jan');
assert.strictEqual(s0.preTaxDeduction, 0);
assert.strictEqual(s0.tax, 0);
assert.strictEqual(s0.netPay, 0);
// Small paycheck enti... | code_purpose_understanding |
16 | devbench-code-purpose-understanding | javascript | class WarehouseReceiving {
constructor() {
this.purchaseOrders = {}; // poId -> { itemId, orderedQty, receivedQty, status }
this.inventory = {}; // itemId -> { available, onHold }
this.lots = []; // { lotId, poId, itemId, qty, status, ts }
this.nextLot = 1;
}
... | receiveShipment(poId, qty, passedInspection, ts) {
const po = this.purchaseOrders[poId];
if (!po) {
return { success: false, reason: 'invalid_po' };
}
if (po.status === 'closed') {
return { success: false, reason: 'po_closed' };
}
const remaini... |
}
const assert = require('assert');
const wh = new WarehouseReceiving();
wh.createPO('PO-001', 'WIDGET-A', 100);
// Receive 50 that pass inspection
const r1 = wh.receiveShipment('PO-001', 50, true, 1000);
assert.strictEqual(r1.success, true);
assert.strictEqual(r1.acceptedQty, 50);
assert.strictEqual(r1.status, 'av... | // Hidden assertions
// Can't receive on closed PO
const r4 = wh.receiveShipment('PO-001', 10, true, 1003);
assert.strictEqual(r4.success, false);
assert.strictEqual(r4.reason, 'po_closed');
// Invalid PO
const r5 = wh.receiveShipment('PO-999', 10, true, 1004);
assert.strictEqual(r5.success, false);
assert.strictEqual... | code_purpose_understanding |
17 | devbench-code-purpose-understanding | javascript | class CreditScorer {
// Tiers: 'poor' (0-399), 'fair' (400-599), 'good' (600-749), 'excellent' (750-850)
static TIERS = [
{ name: 'poor', min: 0, max: 399 },
{ name: 'fair', min: 400, max: 599 },
{ name: 'good', min: 600, max: 749 },
{ name: 'excellent', min: 750, max: 850 },
... | updateScore(factor, weight, ts) {
const delta = Math.round(factor * weight);
const newScore = this._clamp(this.score + delta);
const oldTier = this.tier;
const newTier = this._getTier(newScore);
this.score = newScore;
let tierChanged = false;
if (newTier !== o... |
}
const assert = require('assert');
const cs = new CreditScorer(590, 30); // score 590 = 'fair', 30 unit cooldown
// Bump above 600: triggers transition to 'good'
const u1 = cs.updateScore(5, 3, 100); // delta=15, score=605
assert.strictEqual(u1.score, 605);
assert.strictEqual(u1.tier, 'good');
assert.strictEqual(u... | // Hidden assertions
// No cooldown scorer
const cs2 = new CreditScorer(400, 0);
assert.strictEqual(cs2.tier, 'fair');
// Immediate transitions without cooldown
const h1 = cs2.updateScore(100, 2, 10); // delta=200, score=600
assert.strictEqual(h1.tier, 'good');
assert.strictEqual(h1.tierChanged, true);
const h2 = cs2... | code_purpose_understanding |
18 | devbench-code-purpose-understanding | javascript | class AppointmentScheduler {
constructor(bufferMinutes = 0, cancellationWindowMinutes = 0) {
this.bufferMinutes = bufferMinutes;
this.cancellationWindow = cancellationWindowMinutes;
this.appointments = []; // { id, start, end, recurring, cancelledAt }
this.nextId = 1;
}
_ov... | schedule(start, duration, currentTime = 0) {
const end = start + duration;
for (const apt of this.appointments) {
if (apt.cancelledAt !== null) continue;
// Check overlap including buffer: new appointment must be buffer away from existing
if (this._overlaps(start,... |
}
const assert = require('assert');
const sched = new AppointmentScheduler(15, 60); // 15 min buffer, 60 min cancellation window
// Schedule appointment at time 100, duration 30 (100-130)
const a1 = sched.schedule(100, 30, 0);
assert.strictEqual(a1.success, true);
assert.strictEqual(a1.id, 1);
// Conflict: overlap... | // Hidden assertions
// After cancellation, slot is freed (schedule far from a3 which is at 145-165)
const a5 = sched.schedule(0, 30, 30); // 0-30, buffered -15 to 45, no conflict
assert.strictEqual(a5.success, true);
// Can't cancel already-cancelled appointment
const c3 = sched.cancel(1, 0);
assert.strictEqual(c3.s... | code_purpose_understanding |
19 | devbench-code-purpose-understanding | javascript | class GiftCardSystem {
constructor(maxBalance = 500) {
this.cards = {}; // cardId -> { balance, active, expiresAt, transactions }
this.maxBalance = maxBalance;
}
issueCard(cardId, initialBalance, expiresAt) {
this.cards[cardId] = {
balance: Math.min(initialBalance, this... | activate(cardId, ts) {
const card = this.cards[cardId];
if (!card) return { success: false, reason: 'not_found' };
if (card.active) return { success: false, reason: 'already_active' };
card.active = true;
this._addTransaction(cardId, 'ACTIVATE', 0, card.balance, ts);
... |
}
const assert = require('assert');
const gcs = new GiftCardSystem(500);
gcs.issueCard('GC-001', 200, 9999);
// Must activate before use
const r1 = gcs.redeem('GC-001', 50, 100);
assert.strictEqual(r1.success, false);
assert.strictEqual(r1.reason, 'not_active');
// Activate
const a1 = gcs.activate('GC-001', 100);
... | // Hidden assertions
// Reload at cap
const rl3 = gcs.reload('GC-001', 50, 302);
assert.strictEqual(rl3.success, false);
assert.strictEqual(rl3.reason, 'at_cap');
// Expired card
gcs.issueCard('GC-002', 100, 500);
gcs.activate('GC-002', 100);
const re = gcs.redeem('GC-002', 50, 501);
assert.strictEqual(re.success, fal... | code_purpose_understanding |
20 | devbench-code-purpose-understanding | javascript | class VotingSession {
// passThreshold: fraction of NON-ABSTAIN weighted votes needed (e.g. 0.6 = 60%)
// quorumFraction: fraction of TOTAL possible weight that must vote (including abstain)
constructor(passThreshold, quorumFraction) {
this.passThreshold = passThreshold;
this.quorumFraction ... | castVote(memberId, vote) {
if (this.resolved) {
return { success: false, reason: 'already_resolved' };
}
if (!this.members[memberId]) {
return { success: false, reason: 'not_a_member' };
}
if (!['yes', 'no', 'abstain'].includes(vote)) {
ret... |
}
const assert = require('assert');
const vs = new VotingSession(0.6, 0.5); // 60% pass, 50% quorum
vs.addMember('alice', 3);
vs.addMember('bob', 2);
vs.addMember('carol', 2);
vs.addMember('dave', 1);
// total weight = 8, quorum needs 4
vs.castVote('alice', 'yes'); // 3
vs.castVote('bob', 'no'); // 2
vs.cas... | // Hidden assertions
// No quorum scenario
const vs2 = new VotingSession(0.5, 0.75); // 75% quorum
vs2.addMember('x', 4);
vs2.addMember('y', 4);
vs2.addMember('z', 4); // total 12, quorum needs 9
vs2.castVote('x', 'yes'); // only 4/12 voted
const nr = vs2.resolve();
assert.strictEqual(nr.result, 'no_quorum');
// All... | code_purpose_understanding |
21 | devbench-code-purpose-understanding | javascript | class Warehouse {
constructor(name) {
this.name = name;
this.inventory = {}; // sku -> [{qty, expiry}] sorted by expiry asc
}
addStock(sku, qty, expiry) {
if (!this.inventory[sku]) this.inventory[sku] = [];
this.inventory[sku].push({ qty, expiry });
this.inventory[sk... | transferItems(items) {
if (this.status !== 'pending') throw new Error('Already processed');
const picks = [];
for (const item of items) {
if (this.source.totalQty(item.sku) < item.qty) {
this.status = 'failed';
this.audit.push({ sku: item.sku, reas... |
}
const assert = require('assert');
const w1 = new Warehouse('A'), w2 = new Warehouse('B');
w1.addStock('apple', 5, 100);
w1.addStock('apple', 10, 200);
const t1 = new InventoryTransfer(w1, w2);
t1.transferItems([{ sku: 'apple', qty: 7 }]);
assert.strictEqual(t1.status, 'completed');
assert.strictEqual(w1.totalQty('a... | // Atomic failure: second sku insufficient -> revert first
const w3 = new Warehouse('C'), w4 = new Warehouse('D');
w3.addStock('X', 10, 50);
w3.addStock('Y', 2, 60);
const t2 = new InventoryTransfer(w3, w4);
assert.strictEqual(t2.transferItems([{ sku: 'X', qty: 5 }, { sku: 'Y', qty: 10 }]), false);
assert.strictEqual(t... | code_purpose_understanding |
22 | devbench-code-purpose-understanding | javascript | class InsurancePolicy {
constructor(policyId, basePremium, riskFactor, gracePeriodDays) {
this.policyId = policyId;
this.basePremium = basePremium;
this.riskFactor = riskFactor;
this.gracePeriodDays = gracePeriodDays;
this.status = 'active'; // active | grace | lapsed | reins... | payPremium(day) {
if (this.status !== 'lapsed' && day > this.nextDueDay + this.gracePeriodDays) {
this.status = 'lapsed';
return { accepted: false, reason: 'lapsed' };
}
const isReinstating = this.status === 'lapsed';
const late = !isReinstating && day > this.... |
}
const assert = require('assert');
const p1 = new InsurancePolicy('P1', 100, 1.5, 10);
const r1 = p1.payPremium(30);
assert.strictEqual(r1.amount, 150);
assert.strictEqual(r1.newStatus, 'active');
assert.strictEqual(p1.payments[0].late, false);
assert.strictEqual(p1.nextDueDay, 60);
// Late within grace
const r2 = ... | // Lapse
const p2 = new InsurancePolicy('P2', 200, 1.0, 5);
const r3 = p2.payPremium(36);
assert.strictEqual(r3.accepted, false);
assert.strictEqual(p2.status, 'lapsed');
// Reinstate: penalty applies (200 * 1.25 = 250)
const r4 = p2.payPremium(40);
assert.strictEqual(r4.amount, 250);
assert.strictEqual(r4.newStatus, ... | code_purpose_understanding |
23 | devbench-code-purpose-understanding | javascript | class TaskTracker {
constructor() {
this.tasks = {};
this.completionOrder = [];
}
addTask(id, deps = [], autoComplete = false) {
this.tasks[id] = {
id, deps: [...deps],
status: deps.length > 0 ? 'blocked' : 'ready',
autoComplete, completedAt: null... | completeTask(id, timestamp) {
const task = this.tasks[id];
if (!task) throw new Error('Not found');
if (task.status === 'complete') throw new Error('Already complete');
if (task.status === 'blocked') throw new Error('Blocked');
task.status = 'complete';
task.completed... |
}
const assert = require('assert');
const t = new TaskTracker();
t.addTask('A');
t.addTask('B', ['A']);
t.addTask('C', ['B']);
assert.strictEqual(t.tasks['B'].status, 'blocked');
assert.deepStrictEqual(t.completeTask('A', 100), ['A']);
assert.strictEqual(t.tasks['B'].status, 'ready');
assert.strictEqual(t.tasks['C'].... | // Auto-complete cascade
const t2 = new TaskTracker();
t2.addTask('X');
t2.addTask('Y', ['X'], true);
t2.addTask('Z', ['Y'], true);
t2.addTask('W', ['Z']);
const r = t2.completeTask('X', 1000);
assert.deepStrictEqual(r, ['X', 'Y', 'Z']);
assert.strictEqual(t2.tasks['W'].status, 'ready');
assert.strictEqual(t2.tasks['Y'... | code_purpose_understanding |
24 | devbench-code-purpose-understanding | javascript | class BudgetManager {
constructor(totalBudget, approvalThreshold) {
this.totalBudget = totalBudget;
this.remaining = totalBudget;
this.approvalThreshold = approvalThreshold;
this.departments = {};
this.allocations = [];
this.period = 1;
}
addDepartment(name, ... | allocateBudget(department, amount, approved = false) {
const dept = this.departments[department];
if (!dept) throw new Error('Unknown department');
const effectiveCap = dept.cap + dept.rollover;
if (dept.allocated + amount > effectiveCap)
return { approved: false, reason:... |
}
const assert = require('assert');
const bm = new BudgetManager(1000, 200);
bm.addDepartment('eng', 500);
bm.addDepartment('mkt', 300);
const r1 = bm.allocateBudget('eng', 150);
assert.strictEqual(r1.approved, true);
assert.strictEqual(r1.remaining, 850);
// Needs approval
const r2 = bm.allocateBudget('mkt', 250);
... | // Cap exceeded
const r4 = bm.allocateBudget('mkt', 100);
assert.strictEqual(r4.reason, 'cap_exceeded');
assert.strictEqual(r4.effectiveCap, 300);
// Rollover
bm.newPeriod(500);
assert.strictEqual(bm.departments['mkt'].rollover, 50);
assert.strictEqual(bm.departments['eng'].rollover, 350);
// mkt effective cap = 350,... | code_purpose_understanding |
25 | devbench-code-purpose-understanding | javascript | class MembershipSystem {
constructor() {
this.tiers = [
{ name: 'bronze', minPoints: 0, benefits: ['basic_support'] },
{ name: 'silver', minPoints: 100, benefits: ['basic_support', 'priority_queue'] },
{ name: 'gold', minPoints: 300, benefits: ['basic_support', 'priority_... | processMonth(memberId, pointsEarned, month) {
const m = this.members[memberId];
m.points += pointsEarned;
const q = this._tierForPoints(m.points);
const qIdx = this._tierIndex(q.name), cIdx = this._tierIndex(m.tier);
if (qIdx > cIdx) {
const from = m.tier;
... |
}
const assert = require('assert');
const ms = new MembershipSystem();
ms.addMember('u1');
const s1 = ms.processMonth('u1', 150, 1);
assert.strictEqual(s1.tier, 'silver');
assert.strictEqual(s1.graceMonthsLeft, 2);
assert.deepStrictEqual(s1.benefits, ['basic_support', 'priority_queue']);
assert.strictEqual(ms.member... | // Demotion with grace
const ms2 = new MembershipSystem();
ms2.addMember('u2');
ms2.members['u2'].points = 250;
ms2.members['u2'].tier = 'gold';
ms2.members['u2'].benefits = ['basic_support', 'priority_queue', 'free_shipping'];
ms2.members['u2'].graceMonthsLeft = 2;
const d1 = ms2.processMonth('u2', 0, 10);
assert.str... | code_purpose_understanding |
26 | devbench-code-purpose-understanding | javascript | class SupplyChain {
constructor(minOrderQty) {
this.minOrderQty = minOrderQty;
this.warehouses = {};
this.orders = [];
this.backOrders = [];
this.shipments = [];
}
addWarehouse(name, stock) {
this.warehouses[name] = { stock: { ...stock } };
}
// Fulf... | fulfillOrder(orderId, sku, qty) {
if (qty < this.minOrderQty)
return { fulfilled: false, reason: 'below_moq', minimum: this.minOrderQty };
let remaining = qty, shipmentCount = 0, whIdx = 0;
for (const name of Object.keys(this.warehouses)) {
const avail = this.warehous... |
}
const assert = require('assert');
const sc = new SupplyChain(5);
sc.addWarehouse('WH-East', { widget: 30, gadget: 10 });
sc.addWarehouse('WH-West', { widget: 20, gadget: 5 });
const r1 = sc.fulfillOrder('O1', 'widget', 25);
assert.strictEqual(r1.fulfilledQty, 25);
assert.strictEqual(r1.shipmentCount, 1);
assert.st... | // Partial + back-order
const r3 = sc.fulfillOrder('O3', 'widget', 20);
assert.strictEqual(r3.fulfilledQty, 10);
assert.strictEqual(r3.hasBackOrder, true);
assert.strictEqual(sc.backOrders[0].qty, 10);
// Below MOQ
const r4 = sc.fulfillOrder('O4', 'gadget', 3);
assert.strictEqual(r4.fulfilled, false);
assert.strictEqu... | code_purpose_understanding |
27 | devbench-code-purpose-understanding | javascript | class RateLimiter {
constructor(windowMs, maxRequests, burstAllowance, cooldownMs) {
this.windowMs = windowMs;
this.maxRequests = maxRequests;
this.burstAllowance = burstAllowance;
this.cooldownMs = cooldownMs;
this.requests = [];
this.burstUsed = 0;
this.cool... | tryRequest(timestamp) {
if (timestamp < this.cooldownUntil) {
this.log.push({ timestamp, allowed: false, reason: 'cooldown' });
return { allowed: false, reason: 'cooldown', retryAfter: this.cooldownUntil - timestamp };
}
if (this.cooldownUntil > 0 && timestamp >= this... |
}
const assert = require('assert');
const rl = new RateLimiter(1000, 3, 2, 500);
const r1 = rl.tryRequest(100);
assert.strictEqual(r1.type, 'normal');
assert.strictEqual(r1.remaining, 2);
rl.tryRequest(200);
rl.tryRequest(300);
const r4 = rl.tryRequest(400);
assert.strictEqual(r4.type, 'burst');
assert.strictEqual(... | // Last burst triggers cooldown
const r5 = rl.tryRequest(500);
assert.strictEqual(r5.type, 'burst');
assert.strictEqual(r5.burstRemaining, 0);
// Cooldown
const r6 = rl.tryRequest(600);
assert.strictEqual(r6.reason, 'cooldown');
assert.strictEqual(r6.retryAfter, 400);
assert.strictEqual(rl.tryRequest(999).reason, 'co... | code_purpose_understanding |
28 | devbench-code-purpose-understanding | javascript | class Contract {
constructor(id, totalValue, holdbackPct, penaltyPerDay) {
this.id = id;
this.totalValue = totalValue;
this.holdbackPct = holdbackPct;
this.penaltyPerDay = penaltyPerDay;
this.milestones = [];
this.holdbackPool = 0;
this.totalReleased = 0;
... | acceptDeliverable(milestoneId, acceptDay) {
const ms = this.milestones.find(m => m.id === milestoneId);
if (!ms) throw new Error('Not found');
if (ms.accepted) throw new Error('Already accepted');
const lateDays = Math.max(0, acceptDay - ms.dueDay);
const penalty = Math.min(l... |
}
const assert = require('assert');
const c = new Contract('C1', 10000, 0.10, 50);
c.addMilestone('M1', 3000, 30);
c.addMilestone('M2', 5000, 60);
c.addMilestone('M3', 2000, 90);
const a1 = c.acceptDeliverable('M1', 25);
assert.strictEqual(a1.lateDays, 0);
assert.strictEqual(a1.penalty, 0);
assert.strictEqual(a1.hol... | // Late delivery
const a2 = c.acceptDeliverable('M2', 70);
assert.strictEqual(a2.lateDays, 10);
assert.strictEqual(a2.penalty, 500);
assert.strictEqual(a2.released, 4000);
assert.strictEqual(a2.holdbackReleased, false);
// Last milestone triggers holdback release
const a3 = c.acceptDeliverable('M3', 85);
assert.strict... | code_purpose_understanding |
29 | devbench-code-purpose-understanding | javascript | class ReferralProgram {
constructor(maxDepth, rewardPerLevel, payoutDelayDays) {
this.maxDepth = maxDepth;
this.rewardPerLevel = rewardPerLevel;
this.payoutDelayDays = payoutDelayDays;
this.users = {};
this.pendingPayouts = [];
this.processedPairs = new Set();
}
... | processReferral(referredUserId, day) {
const referred = this.users[referredUserId];
if (!referred || !referred.referredBy)
return { rewarded: false, reason: 'no_referrer' };
let current = referred.referredBy, level = 1, payoutsCreated = 0;
const chain = [];
while ... |
}
const assert = require('assert');
const rp = new ReferralProgram(3, 100, 7);
rp.addUser('A');
rp.addUser('B', 'A');
rp.addUser('C', 'B');
rp.addUser('D', 'C');
const r1 = rp.processReferral('D', 10);
assert.strictEqual(r1.payoutsCreated, 3);
assert.deepStrictEqual(r1.chain, ['C', 'B', 'A']);
assert.strictEqual(rp.... | // Duplicate prevention
const r2 = rp.processReferral('D', 20);
assert.strictEqual(r2.payoutsCreated, 0);
// No referrer
const rp2 = new ReferralProgram(2, 50, 3);
rp2.addUser('X');
assert.strictEqual(rp2.processReferral('X', 5).rewarded, false);
// Depth limit = 1
const rp3 = new ReferralProgram(1, 80, 5);
rp3.addUs... | code_purpose_understanding |
30 | devbench-code-purpose-understanding | javascript | class FairPriorityQueue {
constructor(maxConsecutive, agingBoost) {
this.maxConsecutive = maxConsecutive;
this.agingBoost = agingBoost;
this.items = [];
this.dequeued = [];
this.currentTick = 0;
this.lastCategory = null;
this.consecutiveCount = 0;
}
e... | dequeue() {
if (this.items.length === 0) return null;
const scored = this.items.map((item, idx) => ({
...item, idx,
effectivePriority: item.basePriority + (this.currentTick - item.enqueuedAt) * this.agingBoost
}));
scored.sort((a, b) => b.effectivePriority - a... |
}
const assert = require('assert');
const q = new FairPriorityQueue(2, 5);
q.enqueue('A', 'urgent', 100);
q.enqueue('B', 'normal', 50);
q.enqueue('C', 'urgent', 90);
const d1 = q.dequeue();
assert.strictEqual(d1.id, 'A');
assert.strictEqual(d1.forced, false);
const d2 = q.dequeue();
assert.strictEqual(d2.id, 'C');
... | // Fairness kicks in
const q2 = new FairPriorityQueue(2, 10);
q2.enqueue('h1', 'high', 100);
q2.enqueue('h2', 'high', 95);
q2.enqueue('h3', 'high', 90);
q2.enqueue('l1', 'low', 30);
q2.dequeue(); // h1
q2.dequeue(); // h2
const f3 = q2.dequeue(); // fairness: l1 instead of h3
assert.strictEqual(f3.id, 'l1');
assert.st... | code_purpose_understanding |
31 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class ExpenseReport {
constructor(employeeId, categoryLimits) {
this.employeeId = employeeId;
this.categoryLimits = categoryLimits; // e.g. { travel: 500, meals: 200 }
this.items = [];
this.audit = [];
this.categoryTotals = {};
this.... | addExpense(category, amount, receiptId) {
if (this.status !== 'draft')
return (this.audit.push({ action: 'reject_add', reason: 'not_draft', receiptId }), false);
if (!receiptId || amount <= 0)
return (this.audit.push({ action: 'reject_add', reason: 'invalid_input', receiptId ... |
submit() {
if (this.status !== 'draft' || this.items.length === 0) return false;
this.status = 'submitted';
this.audit.push({ action: 'submit', itemCount: this.items.length });
return true;
}
}
// Basic valid expense
const er = new ExpenseReport('E1', { travel: 500, meals: 200 ... |
// Invalid inputs
const er2 = new ExpenseReport('E2', { meals: 200 });
assert.strictEqual(er2.addExpense('meals', -10, 'R1'), false);
assert.strictEqual(er2.addExpense('meals', 50, ''), false);
assert.strictEqual(er2.addExpense('meals', 50, null), false);
// No category limit means uncapped
assert.strictEqual(er2.add... | code_purpose_understanding |
32 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class SubscriptionManager {
constructor(plans) {
this.plans = plans; // { planName: { price: N, features: [...] } }
this.currentPlan = null;
this.billingStart = 0;
this.cycleLength = 30; // days
this.balance = 0; // credit/debit carried forw... | changePlan(newPlan, day) {
if (!this.currentPlan || newPlan === this.currentPlan || !this.plans[newPlan]) return false;
const daysUsed = day - this.billingStart;
if (daysUsed < 0 || daysUsed > this.cycleLength) return false;
const oldPlan = this.currentPlan;
const remaining =... |
hasFeature(feature) {
if (!this.currentPlan) return false;
return this.plans[this.currentPlan].features.includes(feature);
}
}
const plans = {
basic: { price: 30, features: ['email'] },
pro: { price: 90, features: ['email', 'api', 'support'] },
enterprise: { price: 180, features: [... |
// Cannot change without subscription
const sm2 = new SubscriptionManager(plans);
assert.strictEqual(sm2.changePlan('pro', 5), false);
// Cannot change to invalid plan
const sm3 = new SubscriptionManager(plans);
sm3.subscribe('basic', 0);
assert.strictEqual(sm3.changePlan('invalid', 5), false);
// Day out of cycle r... | code_purpose_understanding |
33 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class Warehouse {
constructor(bins) {
// bins: { binId: { zone: string, capacity: number } }
this.bins = {};
for (const [id, cfg] of Object.entries(bins)) {
this.bins[id] = { ...cfg, items: [], currentLoad: 0 };
}
this.zoneRules ... | assignItem(itemId, itemZone, itemSize, preferredBin) {
const compat = this.zoneRules[itemZone];
if (!compat) return (this.log.push({ action: 'reject', itemId, reason: 'unknown_zone' }), null);
const tryBin = (binId) => {
const bin = this.bins[binId];
if (!bin || !comp... |
evictOldest(binId) {
const bin = this.bins[binId];
if (!bin || bin.items.length === 0) return null;
const item = bin.items.shift(); // FIFO
bin.currentLoad -= item.size;
this.log.push({ action: 'evict', itemId: item.itemId, binId });
return item.itemId;
}
}
cons... |
// Zone compatibility: dry items can go in dry or ambient, not cold/hazmat
const wh2 = new Warehouse({
A1: { zone: 'cold', capacity: 100 },
A2: { zone: 'ambient', capacity: 100 },
A3: { zone: 'dry', capacity: 10 }
});
// Dry item, preferred cold bin A1 incompatible, falls back to A2 (ambient, compatible)
a... | code_purpose_understanding |
34 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class LoyaltyProgram {
constructor(tierMultipliers) {
this.tierMultipliers = tierMultipliers; // { silver: 1, gold: 1.5, platinum: 2 }
this.pointBatches = []; // { points, earnedAt, expiresAt }
this.tier = 'silver';
this.totalEarned = 0;
thi... | burn(amount, currentDay) {
this.pointBatches = this.pointBatches.filter(b => b.expiresAt > currentDay);
let remaining = amount;
const consumed = [];
while (remaining > 0 && this.pointBatches.length > 0) {
const batch = this.pointBatches[0];
if (batch.points <=... |
upgradeTier(newTier) {
if (this.tierMultipliers[newTier] === undefined) return false;
const old = this.tier;
this.tier = newTier;
this.transactions.push({ action: 'upgrade', from: old, to: newTier });
return true;
}
}
const lp = new LoyaltyProgram({ silver: 1, gold: 1.5... |
// Expiry test: earn at day 0, expires at day 365
const lp2 = new LoyaltyProgram({ silver: 1 });
lp2.earn(500, 0);
assert.strictEqual(lp2.availablePoints, 500);
// Burn at day 364: still valid
assert.strictEqual(lp2.burn(100, 364), 100);
assert.strictEqual(lp2.availablePoints, 400);
// Burn at day 365: expired, noth... | code_purpose_understanding |
35 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class ResourceAllocator {
constructor() {
this.resources = {}; // { id: { skills: Set, assignments: [{ projectId, start, end }] } }
this.allocations = [];
}
addResource(id, skills) {
this.resources[id] = { skills: new Set(skills), assignments: [] }... | allocate(projectId, requiredSkills, start, end) {
for (const [id, res] of Object.entries(this.resources)) {
const hasSkills = requiredSkills.every(s => res.skills.has(s));
if (!hasSkills) continue;
const hasConflict = res.assignments.some(a =>
a.start < en... | }
const ra = new ResourceAllocator();
ra.addResource('R1', ['js', 'node']);
ra.addResource('R2', ['js', 'react', 'node']);
ra.addResource('R3', ['python', 'ml']);
// R1 has js + node
assert.strictEqual(ra.allocate('P1', ['js', 'node'], 0, 10), 'R1');
// R1 is busy 0-10, R2 has the skills
assert.strictEqual(ra.alloca... |
// No matching skills
const ra2 = new ResourceAllocator();
ra2.addResource('A', ['java']);
assert.strictEqual(ra2.allocate('X', ['python'], 0, 10), null);
// Partial skill match insufficient
ra2.addResource('B', ['python']);
assert.strictEqual(ra2.allocate('Y', ['python', 'ml'], 0, 10), null);
// Edge case: adjacent... | code_purpose_understanding |
36 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class Invoice {
constructor(id, lineItems) {
this.id = id;
this.lineItems = lineItems.map(li => ({ ...li, paid: 0 })); // { desc, amount, paid }
this.payments = [];
this.credit = 0;
this.status = 'unpaid';
}
get totalDue() {
... | applyPayment(amount, reference) {
if (amount <= 0) return { applied: 0, credit: 0 };
let rem = amount;
const allocs = [];
for (const li of this.lineItems) {
const owed = li.amount - li.paid;
if (owed <= 0) continue;
const a = Math.min(rem, owed);
... | }
const inv = new Invoice('INV-1', [
{ desc: 'Widget A', amount: 100 },
{ desc: 'Widget B', amount: 200 },
{ desc: 'Shipping', amount: 50 }
]);
assert.strictEqual(inv.totalDue, 350);
assert.strictEqual(inv.status, 'unpaid');
// Partial payment of 150: covers Widget A (100) + 50 of Widget B
const r1 = inv... |
// Zero/negative payment
const inv2 = new Invoice('INV-2', [{ desc: 'Item', amount: 100 }]);
assert.deepStrictEqual(inv2.applyPayment(0, 'X'), { applied: 0, credit: 0 });
assert.deepStrictEqual(inv2.applyPayment(-5, 'Y'), { applied: 0, credit: 0 });
assert.strictEqual(inv2.status, 'unpaid');
// Exact payment
inv2.app... | code_purpose_understanding |
37 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class FlightSeating {
constructor(rows) {
// rows: { '1A': { class: 'first', occupied: false, accessible: false }, ... }
this.seats = {};
for (const [id, info] of Object.entries(rows)) {
this.seats[id] = { ...info, passenger: null };
}
... | assignSeat(passengerId, seatId, needsAccessible) {
const seat = this.seats[seatId];
if (!seat || seat.occupied) {
this.manifest.push({ passengerId, seatId, status: 'denied', reason: seat ? 'occupied' : 'invalid' });
return false;
}
if (needsAccessible && !seat... |
upgradePassenger(passengerId) {
const currentSeat = Object.entries(this.seats).find(([_, s]) => s.passenger === passengerId);
if (!currentSeat) return null;
const [oldSeatId, oldSeat] = currentSeat;
const currentIdx = this.classHierarchy.indexOf(oldSeat.class);
if (currentId... |
// Double assignment to same seat
const seats2 = { 'A1': { class: 'economy', occupied: false, accessible: false } };
const fs2 = new FlightSeating(seats2);
assert.strictEqual(fs2.assignSeat('X', 'A1', false), true);
assert.strictEqual(fs2.assignSeat('Y', 'A1', false), false);
assert.strictEqual(fs2.manifest[1].reason,... | code_purpose_understanding |
38 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class ComplianceChecker {
constructor(rules, exceptions) {
// rules: [{ id, check: fn, severity: 'error'|'warning' }] — evaluated in order, first error stops
// exceptions: { ruleId: { grantedTo: [...], expiresAt: number } }
this.rules = rules;
this... | evaluate(entityId, entity, currentDay) {
const results = [];
let blocked = false;
for (const rule of this.rules) {
const exc = this.exceptions[rule.id];
if (exc && exc.grantedTo.includes(entityId) && exc.expiresAt > currentDay) {
results.push({ ruleId:... | }
const rules = [
{ id: 'R1', check: (e) => e.age >= 18, severity: 'error' },
{ id: 'R2', check: (e) => e.certified === true, severity: 'error' },
{ id: 'R3', check: (e) => e.training > 40, severity: 'warning' }
];
const exceptions = {
'R2': { grantedTo: ['E1'], expiresAt: 100 }
};
const cc = new Com... |
// Warning doesn't block
const rules2 = [
{ id: 'W1', check: (e) => e.score > 80, severity: 'warning' },
{ id: 'W2', check: (e) => e.active, severity: 'error' }
];
const cc2 = new ComplianceChecker(rules2, {});
const w = cc2.evaluate('X', { score: 50, active: true }, 0);
assert.strictEqual(w.compliant, true);
... | code_purpose_understanding |
39 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class ReturnProcessor {
constructor(config) {
this.fullRefundDays = config.fullRefundDays; // e.g. 30
this.creditOnlyDays = config.creditOnlyDays; // e.g. 60
this.restockingPct = config.restockingPct; // e.g. 0.15
this.returns = ... | processReturn(orderId, items, orderDay, returnDay) {
const elapsed = returnDay - orderDay;
if (elapsed < 0) return null;
if (elapsed > this.creditOnlyDays) {
this.returns.push({ orderId, status: 'rejected', reason: 'past_return_window', elapsed });
return { status: 'r... | }
const rp = new ReturnProcessor({ fullRefundDays: 30, creditOnlyDays: 60, restockingPct: 0.15 });
// Return within 30 days: full refund, no restocking fee
const r1 = rp.processReturn('O1', [{ price: 50, qty: 2 }], 0, 20);
assert.strictEqual(r1.status, 'approved');
assert.strictEqual(r1.method, 'refund');
assert.stri... |
// Exact boundary: day 30 is full refund
const rp2 = new ReturnProcessor({ fullRefundDays: 30, creditOnlyDays: 60, restockingPct: 0.10 });
const b1 = rp2.processReturn('B1', [{ price: 100, qty: 1 }], 0, 30);
assert.strictEqual(b1.method, 'refund');
assert.strictEqual(b1.restocking, 0);
// Day 31: credit with restocki... | code_purpose_understanding |
40 | devbench-code-purpose-understanding | javascript | const assert = require('assert');
class ShiftScheduler {
constructor(minRestHours, overtimeThreshold) {
this.minRestHours = minRestHours; // minimum hours between shifts
this.overtimeThreshold = overtimeThreshold; // weekly hours before overtime kicks in
this.schedule = {}; // { emp... | assignShift(employeeId, day, start, end) {
if (start >= end) return { ok: false, reason: 'invalid_times' };
const hours = end - start;
if (!this.schedule[employeeId]) { this.schedule[employeeId] = []; this.weeklyHours[employeeId] = 0; }
const shifts = this.schedule[employeeId];
... | }
const ss = new ShiftScheduler(8, 40);
// Normal shift: day 0, 9am-5pm (8 hours)
const s1 = ss.assignShift('E1', 0, 9, 17);
assert.strictEqual(s1.ok, true);
assert.strictEqual(s1.hours, 8);
assert.strictEqual(s1.overtime, 0);
assert.strictEqual(s1.totalWeekly, 8);
// Same day overlap: denied
const s2 = ss.assignShi... |
// Insufficient rest
const ss2 = new ShiftScheduler(10, 40);
ss2.assignShift('A', 0, 14, 22); // ends 22:00 day 0
// Day 1 at 6:00: gap = 24+6 - 22 = 8 hours < 10 minimum
const r = ss2.assignShift('A', 1, 6, 14);
assert.strictEqual(r.ok, false);
assert.strictEqual(r.reason, 'insufficient_rest');
// Day 1 at 8:00: gap... | code_purpose_understanding |
41 | devbench-code-purpose-understanding | javascript | class EscrowAccount {
constructor(totalAmount, holdbackPct = 0.10) {
this.totalAmount = totalAmount;
this.holdbackPct = holdbackPct;
this.milestones = {}; // name -> { required: bool, completed: bool }
this.defects = []; // list of unresolved defect descriptions
... | release(releaseId, timestamp) {
if (this._releaseIds.has(releaseId)) return { status: 'duplicate', amount: 0 };
if (this.defects.length > 0) return { status: 'blocked-defects', amount: 0 };
const unmet = Object.entries(this.milestones)
.filter(([, v]) => v.required && !v.complete... |
}
const esc = new EscrowAccount(10000, 0.10);
esc.addMilestone('design', true);
esc.addMilestone('build', true);
esc.addMilestone('test', false);
// Can't release with incomplete required milestones
let r1 = esc.release('r1', 1000);
console.assert(r1.status === 'milestones-pending', 'Should block on milestones');
e... |
// Second release with different id after first: nothing left (holdback retained)
let r5 = esc.release('r5', 5000);
console.assert(r5.status === 'fully-released', 'Nothing left to release');
console.assert(r5.amount === 0);
// New escrow: optional milestone not blocking
const esc2 = new EscrowAccount(5000, 0.20);
esc... | code_purpose_understanding |
42 | devbench-code-purpose-understanding | javascript | class SLAIncident {
constructor(id, slaLimitMs) {
this.id = id;
this.slaLimitMs = slaLimitMs;
this.state = 'open'; // open -> acknowledged -> paused -> resolved
this.transitions = []; // { from, to, timestamp }
this.openedAt = null;
this.resolvedAt = nul... | transition(newState, timestamp) {
if (!this.openedAt) this.openedAt = timestamp;
const allowed = SLAIncident.VALID_TRANSITIONS[this.state];
if (!allowed || !allowed.includes(newState))
throw new Error(`Invalid: ${this.state} -> ${newState}`);
if (this.state === 'paused') ... |
}
const inc = new SLAIncident('INC-001', 5000); // 5s SLA
inc.transition('acknowledged', 1000);
console.assert(inc.state === 'acknowledged');
console.assert(inc.openedAt === 1000);
// Pause for 3 seconds
inc.transition('paused', 2000);
console.assert(inc.state === 'paused');
// Resume
inc.transition('acknowledged',... |
// Breached scenario
const inc2 = new SLAIncident('INC-002', 2000); // 2s SLA
inc2.transition('acknowledged', 0);
inc2.transition('resolved', 3000); // 3000ms active > 2000ms limit
console.assert(inc2.breached === true, 'Should breach 2s SLA');
// Multiple pause/resume cycles
const inc3 = new SLAIncident('INC-003', 1... | code_purpose_understanding |
43 | devbench-code-purpose-understanding | javascript | class PharmacyDispenser {
constructor() {
this.inventory = {}; // drugName -> quantity
this.dispensedLog = []; // { rxId, drug, qty, copay, timestamp }
this._dispensedRxIds = new Set(); // idempotency
this.dailyControlled = {}; // date_str -> total control... | dispense(rxId, drug, qty, tier, timestamp) {
if (this._dispensedRxIds.has(rxId)) return { status: 'duplicate', copay: 0 };
const info = PharmacyDispenser.DRUGS[drug];
if (!info) return { status: 'unknown-drug', copay: 0 };
if ((this.inventory[drug] || 0) < qty) return { status: 'out-... |
}
const pharm = new PharmacyDispenser();
pharm.addInventory('oxycodone', 100);
pharm.addInventory('ibuprofen', 500);
pharm.addInventory('alprazolam', 50);
// Normal dispense
const d1 = pharm.dispense('rx001', 'oxycodone', 30, 'generic', Date.parse('2026-01-15T10:00:00Z'));
console.assert(d1.status === 'dispensed', '... |
// Non-controlled drug has no daily limit and no refill interval
const d5 = pharm.dispense('rx005', 'ibuprofen', 100, 'generic', Date.parse('2026-01-15T10:00:00Z'));
console.assert(d5.status === 'dispensed');
console.assert(d5.copay === 5);
const d6 = pharm.dispense('rx006', 'ibuprofen', 100, 'brand', Date.parse('2026... | code_purpose_understanding |
44 | devbench-code-purpose-understanding | javascript | class EnrollmentPeriod {
constructor(courseId, capacity, openDate, closeDate) {
this.courseId = courseId;
this.capacity = capacity;
this.openDate = openDate; // timestamp ms
this.closeDate = closeDate; // timestamp ms
this.enrolled = []; // { studentId, priori... | enroll(studentId, priority, timestamp) {
if (timestamp < this.openDate) return { status: 'not-open' };
if (timestamp > this.closeDate) return { status: 'closed' };
if (this._studentIds.has(studentId)) return { status: 'already-enrolled' };
this._studentIds.add(studentId);
if ... |
}
const ep = new EnrollmentPeriod('CS101', 3, 1000, 5000);
// Before open
let e1 = ep.enroll('alice', 2, 500);
console.assert(e1.status === 'not-open', 'Before open date');
// Normal enrollment
let e2 = ep.enroll('alice', 2, 1500);
console.assert(e2.status === 'enrolled', 'Alice enrolled');
console.assert(e2.positi... |
// After close
let e7 = ep.enroll('eve', 1, 6000);
console.assert(e7.status === 'closed', 'After close date');
// Waitlist ordering by priority
let e8 = ep.enroll('frank', 5, 3200);
console.assert(e8.status === 'waitlisted');
console.assert(e8.position === 2, 'Frank behind Dave on waitlist');
// Verify enrolled list... | code_purpose_understanding |
45 | devbench-code-purpose-understanding | javascript | class CommissionEngine {
constructor(quarterlyCap = Infinity) {
this.quarterlyCap = quarterlyCap;
this.deals = {}; // dealId -> { amount, quarter, agentIds, status }
this.earnings = {}; // agentId -> { quarter -> total }
this.auditLog = []; // { action, ... | recordDeal(dealId, amount, quarter, agentIds, timestamp) {
if (this.deals[dealId]) return { status: 'duplicate' };
const totalComm = CommissionEngine.tierRate(amount), split = totalComm / agentIds.length;
this.deals[dealId] = { amount, quarter, agentIds, status: 'active' };
for (cons... |
}
const engine = new CommissionEngine(5000);
// Small deal: 5000 * 5% = 250 commission, split between 2 agents
let r1 = engine.recordDeal('D1', 5000, 'Q1', ['agentA', 'agentB'], 100);
console.assert(r1.status === 'recorded');
console.assert(r1.commission === 250, 'Tiered: 5000 * 5% = 250');
console.assert(engine.ear... |
// Large deal that hits quarterly cap
// tierRate(60000) = 500 + 3200 + 1200 = 4900. Agent A has 2225, cap is 5000.
// So agent A gets min(4900, 5000-2225) = min(4900, 2775) = 2775
let r4 = engine.recordDeal('D3', 60000, 'Q1', ['agentA'], 400);
console.assert(r4.commission === 4900, 'Tiered: 500+3200+1200=4900');
cons... | code_purpose_understanding |
46 | devbench-code-purpose-understanding | javascript | class DonationProcessor {
constructor(annualTaxCap = 50000, matchRatio = 1.0, matchCap = 10000) {
this.annualTaxCap = annualTaxCap; // max deductible per donor per year
this.matchRatio = matchRatio; // employer match ratio (1.0 = dollar-for-dollar)
this.matchCap = matchCap; ... | donate(donorId, amount, year, timestamp) {
if (amount <= 0) return { status: 'invalid-amount' };
const totals = this._getYearTotals(donorId, year);
const matchAvail = Math.max(0, this.matchCap - totals.matched);
const matchAmt = Math.min(amount * this.matchRatio, matchAvail);
... |
}
const dp = new DonationProcessor(50000, 1.0, 10000);
// First donation: $8000, matched $8000 (under cap), deductible $16000 (under cap)
let d1 = dp.donate('donor1', 8000, 2026, 100);
console.assert(d1.status === 'accepted');
console.assert(d1.matched === 8000, 'Full match: 8000*1.0=8000, under 10k cap');
console.a... |
// Different donor has separate caps
let d4 = dp.donate('donor2', 15000, 2026, 400);
console.assert(d4.matched === 10000, 'Match capped at 10000');
console.assert(d4.deductible === 25000, '15000+10000');
console.assert(d4.totalGift === 25000);
// Tax deduction cap test: donor3 donates $40000 (matched $10000 = $50000 ... | code_purpose_understanding |
47 | devbench-code-purpose-understanding | javascript | class FleetVehicle {
constructor(vehicleId, maintIntervalMiles = 5000, maintIntervalDays = 90) {
this.vehicleId = vehicleId;
this.maintIntervalMiles = maintIntervalMiles;
this.maintIntervalDays = maintIntervalDays;
this.currentMiles = 0;
this.lastMaintMiles = 0;
this.... | addMiles(miles, currentDay) {
if (this.state !== 'available') return { status: 'unavailable' };
this.currentMiles += miles;
const milesDue = (this.currentMiles - this.lastMaintMiles) >= this.maintIntervalMiles;
const daysDue = (currentDay - this.lastMaintDay) >= this.maintIntervalDay... |
}
const v = new FleetVehicle('VH-001', 5000, 90);
// Add miles, no maintenance due yet
let m1 = v.addMiles(3000, 10);
console.assert(m1.status === 'ok');
console.assert(m1.maintenanceDue === false, 'Only 3000 miles, not due');
// Add more miles to trigger mileage threshold
let m2 = v.addMiles(2500, 20);
console.ass... |
// Days-based maintenance trigger (no new miles but 90 days pass)
let m6 = v.addMiles(0, 120);
console.assert(m6.maintenanceDue === true, '120-25=95 >= 90 days');
// Start and end another maintenance
v.startMaintenance(120, 'time-based');
v.endMaintenance(122);
console.assert(v.downtimeDays === 7, '5+2=7 total downti... | code_purpose_understanding |
48 | devbench-code-purpose-understanding | javascript | class MenuPricing {
constructor() {
this.items = {}; // name -> { basePrice, happyHourPrice, ingredients: [...] }
this.combos = {}; // comboName -> { items: [name,...], discount: 0.0-1.0 }
this.orders = []; // { items: [...], total, ingredientCost, timestamp }
... | order(itemNames, hour, timestamp) {
const isHH = this._isHappyHour(hour);
let prices = itemNames.map(n => {
const item = this.items[n]; if (!item) throw new Error(`Unknown item: ${n}`);
return isHH ? item.happyHourPrice : item.basePrice;
});
for (const [, comb... |
}
const menu = new MenuPricing();
menu.addItem('burger', 12.00, 9.00, ['beef', 'bun', 'lettuce']);
menu.addItem('fries', 5.00, 3.50, ['potato', 'oil']);
menu.addItem('soda', 3.00, 2.00, ['syrup', 'water']);
menu.addCombo('meal', ['burger', 'fries', 'soda'], 0.15); // 15% off combo
menu.setIngredientCost('beef', 4.00)... |
// Combo + happy hour: (9+3.5+2) * 0.85 = 14.5 * 0.85 = 12.325 -> 12.33
let o4 = menu.order(['burger', 'fries', 'soda'], 16, 4000);
console.assert(o4.total === 12.33, 'Happy hour combo: 14.5*0.85=12.325 rounded');
// Non-combo order at happy hour
let o5 = menu.order(['fries', 'soda'], 17, 5000);
console.assert(o5.tot... | code_purpose_understanding |
49 | devbench-code-purpose-understanding | javascript | class EventTicketing {
constructor(tiers, earlyBirdCutoff, earlyBirdDiscount = 0.20, groupMin = 5, groupDiscount = 0.10) {
// tiers: [{ name, price, capacity }] in order of preference
this.tiers = tiers.map(t => ({ ...t, sold: 0 }));
this.earlyBirdCutoff = earlyBirdCutoff; // timestamp: ear... | book(bookingId, tierName, qty, timestamp) {
if (this._bookingIds.has(bookingId)) return { status: 'duplicate' };
const tier = this.tiers.find(t => t.name === tierName);
if (!tier) return { status: 'unknown-tier' };
if (tier.sold + qty > tier.capacity) return { status: 'insufficient-c... |
}
const evt = new EventTicketing(
[{ name: 'vip', price: 200, capacity: 10 }, { name: 'general', price: 80, capacity: 50 }],
5000, 0.20, 5, 0.10
);
// Early-bird single ticket
let b1 = evt.book('B001', 'vip', 1, 3000);
console.assert(b1.status === 'confirmed');
console.assert(b1.unitPrice === 160, 'Early-bir... |
// Duplicate booking
let b4 = evt.book('B001', 'vip', 1, 7000);
console.assert(b4.status === 'duplicate');
// VIP capacity check: 3 sold so far, 10 capacity
let b5 = evt.book('B005', 'vip', 8, 7000);
console.assert(b5.status === 'insufficient-capacity');
console.assert(b5.available === 7, 'Only 7 VIP left');
// Unkn... | code_purpose_understanding |
50 | devbench-code-purpose-understanding | javascript | class WarrantyManager {
constructor(coverageDurationMs, deductible, annualClaimLimit, laborCoverPct = 0.80) {
this.coverageDurationMs = coverageDurationMs;
this.deductible = deductible; // per-claim deductible
this.annualClaimLimit = annualClaimLimit; // max total payout per year
... | fileClaim(claimId, productId, partsCost, laborCost, timestamp) {
if (this._claimIds.has(claimId)) return { status: 'duplicate', payout: 0, customerOwes: 0 };
const product = this.products[productId];
if (!product) return { status: 'unknown-product', payout: 0, customerOwes: 0 };
if (... |
}
// 1 year warranty, $100 deductible, $5000 annual limit, 80% labor coverage
const wm = new WarrantyManager(365 * 24 * 3600 * 1000, 100, 5000, 0.80);
const purchaseDate = Date.parse('2026-01-01T00:00:00Z');
wm.registerProduct('P001', purchaseDate, 'Alice');
// Claim within warranty: parts $300, labor $200
// cover... |
// Annual limit test: 5000 limit, already used 360
// Large claim: parts $4000, labor $2000
// coveredLabor = 2000*0.80 = 1600, totalCoverable = 4000+1600 = 5600
// afterDeductible = 5600-100 = 5500. yearAvail = 5000-360 = 4640
// payout = min(5500, 4640) = 4640
let c4 = wm.fileClaim('C004', 'P001', 4000, 2000, Date.p... | code_purpose_understanding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.