mirror of
https://github.com/zaphar/ucg.git
synced 2025-07-21 18:10:42 -04:00
DEV: Add an integer parsing operation for string.
This commit is contained in:
parent
7b28fd9d6c
commit
2155bc0308
@ -20,6 +20,7 @@ let ops = module {
|
||||
split_on=split_on,
|
||||
split_at=split_at,
|
||||
substr=substr,
|
||||
parse_int=parse_int,
|
||||
}) {
|
||||
let len = import "std/lists.ucg".len(mod.str);
|
||||
let str = mod.str;
|
||||
@ -89,6 +90,36 @@ let ops = module {
|
||||
)
|
||||
);
|
||||
|
||||
let parse_int = module{
|
||||
str = mod.str,
|
||||
start = 0,
|
||||
end = len,
|
||||
} => (f.maybe{val=result}) {
|
||||
let pkg = mod.pkg();
|
||||
let f = import "std/functional.ucg";
|
||||
|
||||
let reducer = func(acc, char) => acc{
|
||||
str = select (char, acc.str) => {
|
||||
"1" = acc.str + char,
|
||||
"2" = acc.str + char,
|
||||
"3" = acc.str + char,
|
||||
"4" = acc.str + char,
|
||||
"5" = acc.str + char,
|
||||
"6" = acc.str + char,
|
||||
"7" = acc.str + char,
|
||||
"8" = acc.str + char,
|
||||
"9" = acc.str + char,
|
||||
"0" = acc.str + char,
|
||||
},
|
||||
};
|
||||
let num = reduce(
|
||||
reducer, {counter = 0, str = ""}, mod.str).str;
|
||||
let result = select (num != "", NULL) => {
|
||||
true = int(num),
|
||||
false = NULL,
|
||||
};
|
||||
};
|
||||
|
||||
let substr = module{
|
||||
str = mod.str,
|
||||
start = 0,
|
||||
|
@ -51,4 +51,15 @@ assert t.equal{
|
||||
assert t.equal{
|
||||
left = str_class.substr{end=8}.str,
|
||||
right = "foo bar",
|
||||
};
|
||||
|
||||
assert t.equal{
|
||||
left = strings.ops{str="123"}.parse_int{}.unwrap(),
|
||||
right = 123,
|
||||
};
|
||||
|
||||
let str_int = strings.ops{str="123"};
|
||||
assert t.equal{
|
||||
left = strings.ops{str="123 "}.parse_int{}.unwrap(),
|
||||
right = 123,
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user