diff --git a/ascii.libsonnet b/ascii.libsonnet index 65d6473..f7962d0 100644 --- a/ascii.libsonnet +++ b/ascii.libsonnet @@ -26,4 +26,10 @@ local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet'; [d.arg('c', d.T.string)] ), isNumber(c): std.isNumber(c) || (cp(c) >= 48 && cp(c) < 58), + + '#isStringNumeric':: d.fn( + '`isStringNumeric` reports whether string `s` consists only of numeric characters.', + [d.arg('str', d.T.string)] + ), + isStringNumeric(str): std.all(std.map(self.isNumber, std.stringChars(str))), } diff --git a/docs/ascii.md b/docs/ascii.md index 9a85053..1ad7288 100644 --- a/docs/ascii.md +++ b/docs/ascii.md @@ -14,6 +14,7 @@ local ascii = import "github.com/jsonnet-libs/xtd/ascii.libsonnet" * [`fn isLower(c)`](#fn-islower) * [`fn isNumber(c)`](#fn-isnumber) +* [`fn isStringNumeric(str)`](#fn-isstringnumeric) * [`fn isUpper(c)`](#fn-isupper) ## Fields @@ -34,6 +35,14 @@ isNumber(c) `isNumber` reports whether character `c` is a number. +### fn isStringNumeric + +```ts +isStringNumeric(str) +``` + +`isStringNumeric` reports whether string `s` consists only of numeric characters. + ### fn isUpper ```ts diff --git a/test/ascii_test.jsonnet b/test/ascii_test.jsonnet new file mode 100644 index 0000000..077b350 --- /dev/null +++ b/test/ascii_test.jsonnet @@ -0,0 +1,44 @@ +local ascii = import '../ascii.libsonnet'; +local test = import 'github.com/jsonnet-libs/testonnet/main.libsonnet'; + +test.new(std.thisFile) + ++ test.case.new( + name='all numeric', + test=test.expect.eq( + actual=ascii.isStringNumeric('123'), + expected=true, + ) +) + ++ test.case.new( + name='only beginning numeric', + test=test.expect.eq( + actual=ascii.isStringNumeric('123abc'), + expected=false, + ) +) + ++ test.case.new( + name='only end numeric', + test=test.expect.eq( + actual=ascii.isStringNumeric('abc123'), + expected=false, + ) +) + ++ test.case.new( + name='none numeric', + test=test.expect.eq( + actual=ascii.isStringNumeric('abc'), + expected=false, + ) +) + ++ test.case.new( + name='empty', + test=test.expect.eq( + actual=ascii.isStringNumeric(''), + expected=true, + ) +)