Youtube 頻道:https://www.youtube.com/c/kaochenlong
如果畫面太小或看不清楚
可移駕至 https://www.youtube.com/watch?v=8_4jfG2eqNc 觀看 4K 高畫質版本
GitHub 專案:https://github.com/kaochenlong/cann-lang
如果喜歡這個系列的影片,歡迎訂閱我的頻道
或是想聽我介紹一些別的內容,也可直接在這裡或 YouTube 頁面下方留言 :)
檔案:src/parser.ts
class Parser {
parse() {
return {
type: "Program",
body: {
type: "NUMBER",
value: 1450,
},
}
}
}
export { Parser }
檔案:src/tokenizer.ts
@@ -23,16 +23,14 @@ class Tokenizer {
// 如果是數字的話...
if (isNumber(str[0])) {
- let result = ""
-
- while (isNumber(str[this.cursor])) {
- result += str[this.cursor]
- this.cursor++
- }
-
- return {
- type: "NUMBER",
- value: +result,
+ const matched = /\d+/.exec(str)
+ if (matched !== null) {
+ this.cursor += matched[0].length
+
+ return {
+ type: "NUMBER",
+ value: +matched[0],
+ }
}
}
檔案:tests/parser.test.js
import { describe, it } from "https://deno.land/std@0.156.0/testing/bdd.ts"
import { expect } from "https://deno.land/x/expect@v0.2.10/mod.ts"
import { Parser } from "../src/parser.ts"
describe("Parser", () => {
it("可以處理數字", () => {
const input = `1450`
const result = {
type: "Program",
body: {
type: "NUMBER",
value: 1450,
},
}
const p = new Parser()
expect(p.parse(input)).toEqual(result)
})
})