Skip to content

Commit 6f1e795

Browse files
awearyBrandon Dail
authored andcommitted
feat: Improve internal comments for parser/compiler (#3)
1 parent 316c53c commit 6f1e795

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/compiler.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,15 @@ function suffix(int: number): string {
7070
: int + "th";
7171
}
7272

73+
/**
74+
* The compiler takes in our array of tokens returned from the parser
75+
* and returns the formed template. It just iterates over the tokens and
76+
* appends some text to the returned string depending on the type of token.
77+
* @param {Array<Tokens>} tokens
78+
* @param {Date} date
79+
* @param {TinyTimeOptions} options
80+
* @returns {String}
81+
*/
7382
export default function compiler(tokens: Array<Token>, date: Date, options: TinyTimeOptions): string {
7483
const month = date.getMonth();
7584
const year = date.getFullYear();

src/parser.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,37 @@ export type Token = {
2727
*/
2828
export default function parser(template: string): Array<Token> {
2929
const tokens: Array<Token> = []
30+
/**
31+
* We iterate through each character in the template string, and track
32+
* the index of the character we're processing with `position`. We start
33+
* at 0, the first character.
34+
*/
3035
let position = 0
36+
/**
37+
* `text` is used to accumulate what we call "UserText", or simply text that
38+
* is not a subsitution. For example, in the template:
39+
*
40+
* "The day is {day}."
41+
*
42+
* There are two instances of `UserText`, "The day is " and ".", which is the text
43+
* befor eand after the subsitution. With this template our tokens would look something like:
44+
*
45+
* [
46+
* { type: UserText, value: "The day is "},
47+
* { type : DaySub },
48+
* { type: UserText, value: "." }
49+
* ]
50+
*
51+
*/
3152
let text = ''
3253
while (position < template.length) {
3354
let char = template[position++];
55+
/**
56+
* A bracket indicates we're starting a subsitution. Any characters after this,
57+
* and before the next '}' will be considered part of the subsitution name.
58+
*/
3459
if (char === '{') {
60+
// Push any `UserText` we've accumulated and reset the `text` variable.
3561
if (text) {
3662
tokens.push({
3763
t: UserText,
@@ -54,6 +80,10 @@ export default function parser(template: string): Array<Token> {
5480
text += char
5581
}
5682
}
83+
/**
84+
* We might have some text after we're done iterating through the template if
85+
* the template ends with some `UserText`.
86+
*/
5787
if (text) {
5888
tokens.push({
5989
t: UserText,

0 commit comments

Comments
 (0)