簡體   English   中英

創建計算器 (JS)

[英]Create calculator (JS)

我有一行calc(2).add(3).add(5).res()並且需要編寫一個解決方案,以便我有10作為結果。 我試過這個

 class Calc{ constructor(num){ this.num = num } add(a){ this.num += a; return this; } res() { return this.num; } } let calc = new Calc(2) console.log(calc.add(3).add(5).res())

但在我的情況下,我在new Calc(2)傳遞2 ,而不是在calc(2) 我怎樣才能改變它?

將不勝感激任何幫助!

如果我理解正確,這將是一種方法:

 class Calc{ constructor(num){ this.num = num } add(a){ this.num += a; return this; } res() { return this.num; } } let calc = function(num){ return new Calc(num) } console.log(calc(2).add(3).add(5).res())

你可以有一個優雅的解決方案,利用閉包的力量:

 function calc(x) { return { res: function() { return x; }, add: function(y) { return calc(x + y) } } } test( 10, calc(10).res() ); test( 10, calc(3).add(7).res() ); test( 10, calc(8).add(2).res() ); test( 10, calc(2).add(3).add(5).res() ); function test(expected, actual) { console.log( `result is: ${actual} correct: ${actual === expected} `) }

calc函數采用名為x的初始數字並返回一個具有兩種方法的對象:

  • res()只返回數字
  • add()將接受一個參數y ,將它與x相加並再次使用結果調用calc

所以你的界面是完全一致的: calc(10)將與calc(3).add(7)calc(8).add(2)calc(2).add(3).add(5) 您可以根據需要盡可能多地鏈接add調用,並且它總是相同的。 調用res()將結束鏈並只給你calc當前持有的數字 - 無論你已經完成了calc(10).res()還是calc(2).add(3).add(5).res()

使用箭頭函數可以大大縮短代碼:

 const calc = x => ({ res: () => x, add: y => calc(x + y) }); test( 10, calc(10).res() ); test( 10, calc(3).add(7).res() ); test( 10, calc(8).add(2).res() ); test( 10, calc(2).add(3).add(5).res() ); function test(expected, actual) { console.log( `result is: ${actual} correct: ${actual === expected} `) }

使用相同的模式也可以輕松添加其他操作:

 const calc = x => ({ res: () => x, add: y => calc(x + y), sub: y => calc(x - y), mul: y => calc(x * y), div: y => calc(x / y) }); test( 2, calc(5).add(5).mul(2).sub(4).div(8).res() // (((5 + 5) * 2) - 4) / 8 = // ((10 * 2) - 4) / 8 = // (20 - 4) / 8 = // 16 / 8 = 2 ); function test(expected, actual) { console.log( `result is: ${actual} correct: ${actual === expected} `) }

請注意,由於每個操作都是立即執行的,因此您當前擁有的唯一優先級是最先出現的。

您可以將calc定義為返回 Calc 對象的函數。

 class Calc{ constructor(num){ this.num = num } add(a){ this.num += a; return this; } res() { return this.num; } } const calc = (input) => new Calc(input); console.log(calc(2).add(3).add(5).res())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2025 STACKOOM.COM