鍍金池/ 教程/ HTML/ 解釋器模式
備忘錄模式
解釋器模式
類似 Python 的 zip 函數(shù)
類變量和實例變量
提示參數(shù)
指數(shù)對數(shù)運算
檢查變量的類型是否為數(shù)組
由數(shù)組創(chuàng)建一個字符串
生成隨機數(shù)
刪除數(shù)組中的相同元素
大寫單詞首字母
雙向服務器
類的混合
計算復活節(jié)的日期
轉(zhuǎn)換弧度和度
找到上一個月(或下一個月)
雙向客戶端
橋接模式
嵌入 JavaScript
AJAX
觀察者模式
克隆對象(深度復制)
一個隨機整數(shù)函數(shù)
清理字符串前后的空白符
歸納數(shù)組
平方根倒數(shù)快速算法
適配器模式
打亂數(shù)組中的元素
將數(shù)組連接
使用數(shù)組來交換變量
更快的 Fibonacci 算法
服務器
服務端和客戶端的代碼重用
客戶端
查找子字符串
策略模式
CoffeeScrip 的 type 函數(shù)
由數(shù)組創(chuàng)建一個對象詞典
回調(diào)綁定
工廠方法模式
映射數(shù)組
當函數(shù)括號不可選
生成可預測的隨機數(shù)
不使用 jQuery 的 Ajax 請求
把字符串轉(zhuǎn)換為小寫形式
類方法和實例方法
擴展內(nèi)置對象
定義數(shù)組范圍
MongoDB
匹配字符串
創(chuàng)建一個不存在的對象字面值
列表推導
比較范圍
修飾模式
檢測每個元素
拆分字符串
字符串插值
對象數(shù)組
去抖動函數(shù)
使用 Nodeunit 測試
SQLite
單件模式
篩選數(shù)組
替換子字符串
數(shù)組最大值
計算(美國和加拿大的)感恩節(jié)日期
找到一個月中的最后一天
計算兩個日期中間的天數(shù)
基本的 HTTP 服務器
把字符串轉(zhuǎn)換為大寫形式
使用 HTML 命名實體替換 HTML 標簽
For 循環(huán)
模板方法模式
重復字符串
使用 Jasmine 測試
對象的鏈式調(diào)用
數(shù)學常數(shù)
反轉(zhuǎn)數(shù)組
計算月球的相位
使用 Heregexes
查找子字符串
生成器模式
遞歸函數(shù)
HTTP 客戶端
創(chuàng)建 jQuery 插件
檢測與構(gòu)建丟失的函數(shù)
生成唯一ID
命令模式

解釋器模式

問題

其他人需要以控制方式運行你的一部分代碼。相對地,你選擇的語言不能以一種簡潔的方式表達問題域。

解決方案

使用解釋器模式來創(chuàng)建一個你翻譯為特定代碼的領域特異性語言( domain-specific language )。

我們來做個假設,例如用戶希望在你的應用程序中執(zhí)行數(shù)學運算。你可以讓他們正向運行代碼來演算指令(eval)但這會讓他們運行任意代碼。相反,你可以提供一個小型的“堆棧計算器(stack calculator)”語言,用來做單獨分析,以便只運行數(shù)學運算,同時報告更有用的錯誤信息。

class StackCalculator
    parseString: (string) ->
        @stack = [ ]
        for token in string.split /\s+/
            @parseToken token

        if @stack.length > 1
            throw "Not enough operators: numbers left over"
        else
            @stack[0]

    parseToken: (token, lastNumber) ->
        if isNaN parseFloat(token) # Assume that anything other than a number is an operator
            @parseOperator token
        else
            @stack.push parseFloat(token)

    parseOperator: (operator) ->
        if @stack.length < 2
            throw "Can't operate on a stack without at least 2 items"

        right = @stack.pop()
        left = @stack.pop()

        result = switch operator
            when "+" then left + right
            when "-" then left - right
            when "*" then left * right
            when "/"
                if right is 0
                    throw "Can't divide by 0"
                else
                    left / right
            else
                throw "Unrecognized operator: #{operator}"

        @stack.push result

calc = new StackCalculator

calc.parseString "5 5 +" # => { result: 10 }

calc.parseString "4.0 5.5 +" # => { result: 9.5 }

calc.parseString "5 5 + 5 5 + *" # => { result: 100 }

try
    calc.parseString "5 0 /"
catch error
    error # => "Can't divide by 0"

try
    calc.parseString "5 -"
catch error
    error # => "Can't operate on a stack without at least 2 items"

try
    calc.parseString "5 5 5 -"
catch error
    error # => "Not enough operators: numbers left over"

try
    calc.parseString "5 5 5 foo"
catch error
    error # => "Unrecognized operator: foo"

討論

作為一種替代編寫我們自己的解釋器的選擇,你可以將現(xiàn)有的 CoffeeScript 解釋器與更自然的(更容易理解的)表達自己的算法的正常方式相結(jié)合。

class Sandwich
    constructor: (@customer, @bread='white', @toppings=[], @toasted=false)->

white = (sw) ->
    sw.bread = 'white'
    sw

wheat = (sw) ->
    sw.bread = 'wheat'
    sw

turkey = (sw) ->
    sw.toppings.push 'turkey'
    sw

ham = (sw) ->
    sw.toppings.push 'ham'
    sw

swiss = (sw) ->
    sw.toppings.push 'swiss'
    sw

mayo = (sw) ->
    sw.toppings.push 'mayo'
    sw

toasted = (sw) ->
    sw.toasted = true
    sw

sandwich = (customer) ->
    new Sandwich customer

to = (customer) ->
    customer

send = (sw) ->
    toastedState = sw.toasted and 'a toasted' or 'an untoasted'

    toppingState = ''
    if sw.toppings.length > 0
        if sw.toppings.length > 1
            toppingState = " with #{sw.toppings[0..sw.toppings.length-2].join ', '} and #{sw.toppings[sw.toppings.length-1]}"
        else
            toppingState = " with #{sw.toppings[0]}"
    "#{sw.customer} requested #{toastedState}, #{sw.bread} bread sandwich#{toppingState}"

send sandwich to 'Charlie' # => "Charlie requested an untoasted, white bread sandwich"
send turkey sandwich to 'Judy' # => "Judy requested an untoasted, white bread sandwich with turkey"
send toasted ham turkey sandwich to 'Rachel' # => "Rachel requested a toasted, white bread sandwich with turkey and ham"
send toasted turkey ham swiss sandwich to 'Matt' # => "Matt requested a toasted, white bread sandwich with swiss, ham and turkey"

這個實例可以允許功能層實現(xiàn)返回修改后的對象,從而外函數(shù)可以依次修改它。示例通過借用動詞和介詞的用法,把自然語法提供給結(jié)構(gòu),當被正確使用時,會像自然語句一樣結(jié)束。這樣,利用 CoffeeScript 語言技能和你現(xiàn)有的語言技能可以幫助你關于捕捉代碼的問題。