-
-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(fsm): update str() to NOT collect input by default (match only)
- Loading branch information
1 parent
ccc9d40
commit 6105ea7
Showing
1 changed file
with
37 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,49 @@ | ||
import { LitCallback, Match, Matcher, RES_PARTIAL } from "./api"; | ||
import { | ||
LitCallback, | ||
Match, | ||
Matcher, | ||
RES_PARTIAL | ||
} from "./api"; | ||
import { result } from "./result"; | ||
|
||
/** | ||
* String-only version of `seq()`. Returns `Match.FULL` once the entire | ||
* given string could be matched. | ||
* given string could be matched. Unless `collect` is true (default: | ||
* false), only matches given string and does not collect input. | ||
* Therefore then also only passes an empty string to `fail` callback. | ||
* If `collect` is true, the failed callback will be called with the | ||
* collected input. | ||
* | ||
* @param str | ||
* @param success | ||
* @param fail | ||
* @param collect | ||
*/ | ||
export const str = <C, R>( | ||
str: string, | ||
success?: LitCallback<string, C, R>, | ||
fail?: LitCallback<string, C, R> | ||
): Matcher<string, C, R> => () => { | ||
let buf = ""; | ||
return (ctx, x) => | ||
(buf += x) === str | ||
? result(success && success(ctx, buf)) | ||
: str.indexOf(buf) === 0 | ||
? RES_PARTIAL | ||
: result(fail && fail(ctx, buf), Match.FAIL); | ||
}; | ||
fail?: LitCallback<string, C, R>, | ||
collect = false | ||
): Matcher<string, C, R> => | ||
collect | ||
? () => { | ||
let buf = ""; | ||
return (ctx, x) => | ||
(buf += x) === str | ||
? result(success && success(ctx, buf)) | ||
: str.indexOf(buf) === 0 | ||
? RES_PARTIAL | ||
: result(fail && fail(ctx, buf), Match.FAIL); | ||
} | ||
: () => { | ||
let matched = 0; | ||
let i = 0; | ||
return (ctx, x) => { | ||
str.charAt(i++) === x && matched++; | ||
return matched === str.length | ||
? result(success && success(ctx, str)) | ||
: matched === i | ||
? RES_PARTIAL | ||
: result(fail && fail(ctx, ""), Match.FAIL); | ||
}; | ||
}; |