2017-09-18 50 views
0

我試圖將Paul Heggarty爲課程CS193p(斯坦福大學,2017年冬季)創建的Swift計算器轉換爲Typescript代碼(本例中爲Ionic 3(Angular 4)),以查看差異。在Typescript/Javascript中快速關閉

我並不專注於盡可能以相同的方式做。

我已經走得很遠了,但我在打字稿中做了以下工作。

private var operations: Dictionary<String,Operation> = [ 
     "+" : Operation.binaryOperation({ $0 + $1 }), 
     "−" : Operation.binaryOperation({ $0 - $1 }), 
     "÷" : Operation.binaryOperation({ $0/$1 }), 
     "×" : Operation.binaryOperation({ $0 * $1 }), 
     "π" : Operation.constant(Double.pi), 
     "√" : Operation.preFixUnaryOperation(sqrt), 
     "x²" : Operation.postFixUnaryOperation({ pow($0, 2) }), 
     "x³" : Operation.postFixUnaryOperation({ pow($0, 3) }), 
     "=" : Operation.equals, 
     "±" : Operation.preFixUnaryOperation({ -$0 }), 
     "sin": Operation.preFixUnaryOperation(sin), 
     "cos": Operation.preFixUnaryOperation(cos), 
     "tan": Operation.preFixUnaryOperation(tan), 
     "e" : Operation.constant(M_E) 
    ] 

我到目前爲止所做的是創建一個私有變量,名爲「operations」,類型爲「{}」。

然後通過調用 「補」 是:

this.operations['+' = Operation.binaryOperation(() => {arguments[0] + argumenst[1]}) 

灌裝部分不工作。除了我不知道如何解析這樣的功能。在斯威夫特

枚舉操作:在打字稿

private enum Operation { 
    case constant(Double) 
    case preFixUnaryOperation((Double) -> Double) 
    case postFixUnaryOperation((Double) -> Double) 
    case binaryOperation((Double,Double) -> Double) 
    case equals 
} 

枚舉操作(同樣的問題):

export enum Operation { 
    constant, // Double is an assosiative value, its like the assosiated value in the 'set' state of an optional. 
    preFixUnaryOperation, 
    postFixUnaryOperation, 
    binaryOperation, 
    equals 
} 

我應該如何使用,這就是所謂的斯威夫特, 「關閉」,以打字稿/ JavaScript的?

回答

1

我認爲你的問題是關於Associated Values,而不是自己約Closures

打字稿有關聯的值並不能完全模擬,但你可以做這樣的事情:

const enum Operation { 
    preFixUnaryOperation, 
    postFixUnaryOperation, 
    binaryOperation 
} 

type IOperation = { 
    type: Operation.preFixUnaryOperation | Operation.postFixUnaryOperation; 
    func: (a: number) => number; 
} | { 
    type: Operation.binaryOperation; 
    func: (a: number, b: number) => number; 
} 

let operations: {[key: string]: IOperation} = { 
    '+': { type: Operation.binaryOperation, func: (a, b) => a + b }, 
    'x²': { type: Operation.postFixUnaryOperation, func: (a) => a * a } 
}; 

let operation = operations[someKey]; 

switch (operation.type) { 
    case Operation.binaryOperation: 
    return operation.func(left, right); 
    case Operation.preFixUnaryOperation: 
    return operation.func(right);  
    case Operation.postFixUnaryOperation: 
    return operation.func(left); 
} 

參見:Discriminated Unions