Labeled Tuple Elements In Parser Results
Document each slot of a fixed-shape return with labeled tuple elements, so destructured parser results read clearly at the call site while staying plain arrays.
Code
// labeled tuple elements: 每个槽位都有名字,本质仍是普通数组
type Scan = [value: number, rest: string] | null;
function scanInt(input: string): Scan {
let i = 0;
let sign = 1;
if (input[i] === '-' || input[i] === '+') {
sign = input[i] === '-' ? -1 : 1;
i += 1;
}
const start = i;
while (i < input.length && input[i] >= '0' && input[i] <= '9') i += 1;
if (i === start) return null; // 没有前导数字
return [sign * Number(input.slice(start, i)), input.slice(i)];
}
const samples = ['42px', '-7kg', '+1005ms', 'none'];
for (const sample of samples) {
const scanned = scanInt(sample);
if (!scanned) {
console.log(sample, '-> no leading integer');
continue;
}
const [value, rest] = scanned; // 解构出的 value / rest 对应标签
console.log(sample, '-> value =', value, 'rest =', JSON.stringify(rest));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
42px -> value = 42 rest = "px"
-7kg -> value = -7 rest = "kg"
+1005ms -> value = 1005 rest = "ms"
none -> no leading integerHow the snippet works
Count the function scanInt as the entire surface area of Labeled Tuple Elements In Parser Results.
while (i < input.length && input[i] >= '0' && input[i] <= '9') i += 1; and for (const sample of samples) nest, one inside the other.
What comes back is a new object, not a reference to anything passed in.
Points of care
- The guard
i === startshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads function scanInt(input: string)
Statements that matter
while (i < input.length && input[i] >= '0' && input[i] <= '9') i += 1;
return [sign * Number(input.slice(start, i)), input.slice(i)];
Interactive Tools for This Topic
FAQ
- Does `scanInt` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `scanInt` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.