Skip to content

Commit cdeb2a6

Browse files
committed
Implement str2nr()
1 parent 3786a02 commit cdeb2a6

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/vimscript/expression/evaluate.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1193,7 +1193,16 @@ export class EvaluationContext {
11931193
}
11941194
return list(result.map(int));
11951195
}
1196-
// TODO: str2nr()
1196+
case 'str2nr': {
1197+
const [s, _base] = getArgs(1, 2);
1198+
const base = _base ? toInt(_base) : 10
1199+
if (![2, 8, 10, 16].includes(base)) {
1200+
throw VimError.fromCode(ErrorCode.InvalidArgument474);
1201+
}
1202+
// TODO: Skip prefixes like 0x
1203+
const parsed = Number.parseInt(toString(s!), base)
1204+
return int(isNaN(parsed) ? 0 : parsed);
1205+
}
11971206
// TODO: stridx()
11981207
case 'string': {
11991208
const [x] = getArgs(1);

test/vimscript/expression.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -733,6 +733,16 @@ suite('Vimscript expressions', () => {
733733
exprTest('str2list("á")', { value: list([int(97), int(769)]) });
734734
});
735735

736+
suite('str2nr', () => {
737+
exprTest('str2nr("123")', { value: int(123) });
738+
exprTest('str2nr("1001010110", 2)', { value: int(598) });
739+
exprTest('str2nr("123", 8)', { value: int(83) });
740+
exprTest('str2nr("123", 10)', { value: int(123) });
741+
exprTest('str2nr("DEADBEEF", 16)', { value: int(3735928559) });
742+
exprTest('str2nr("DEADBEEF", 10)', { value: int(0) });
743+
exprTest('str2nr("DEADBEEF", 9)', { error: ErrorCode.InvalidArgument474 });
744+
});
745+
736746
suite('string', () => {
737747
exprTest('string("")', { value: str('') });
738748
exprTest('string(123)', { value: str('123') });

0 commit comments

Comments
 (0)