]> git.kianting.info Git - uann/blob - src/index.ts
3c3384d520bc8bf8d6e54bd6f00bbf47cf909ee2
[uann] / src / index.ts
1 var fs = require('fs');
2
3 type Some<T> = { _tag: "Some"; value: T };
4 type None = {_tag: "None"};
5
6 /**
7 * @description Like the `Some(a)` and `None` in Rust.
8 *
9 * @example
10 * ```ts
11 * let exam1 : Maybe<Number> = { _tag: "Some", value: 12 };
12 * let exam2 : Maybe<Number> = None;
13 * ```
14 */
15 export type Maybe<T> = Some<T> | None;
16
17
18 /**
19 * @description
20 * the pair of the string to be matched later and the string that have been matched
21 * @param matched : string have been matched
22 * @param remained : string will be tested whether it'll be matched.
23 */
24 export type MatcheePair = {matched : string; remained : string};
25
26 /**
27 * @description
28 * it returns a function which test if the first char of the `remained` part of
29 * the argument of the function is `c`, if it's true, update the `MatchedPair` wrapped
30 * in `Some`. Otherwise, it returns `None`.
31 * * @param c : the char to be test.
32 * @returns the updated `MatchedPair` wrapped in `Some(x)` or `None`.
33 */
34 export function match1Char(c : string) : (m: MatcheePair) => Maybe<MatcheePair> {
35 return (m : MatcheePair)=>{
36 const charToBeMatched = m.remained[0];
37 if (charToBeMatched === c){
38 return {_tag: "Some", value :{
39 matched : m.matched + charToBeMatched,
40 remained : m.remained.substring(1)}};
41 }
42 else{
43 return {_tag: "None"};
44 }
45 }
46 };
47
48 /**
49 * convert the one-char string to codepoint.
50 * @param s : the string to code point.
51 * @returns if `s.length > 1` return error; otherwise, return the codepoint of `s`.
52 */
53 export function charToCodepoint(s : string): number{
54 if (s.length > 1){
55 throw new Error("Error: the length of input string for "+s+ "is "+s.length+`,
56 however, it should be 1.`);
57 }else{
58 return s.charCodeAt(0);
59 }
60 }
61
62 /**
63 * @description thendo(input, f, ...) like
64 * a ==> f
65 */
66 export function thenDo<T>(input : Maybe<T>, f : Function) : Maybe<T>{
67 if (input._tag == "None"){
68 return input;
69 }
70 else{
71 let inner = input.value;
72 return f(inner);
73 }
74 }