Created
January 19, 2017 16:11
-
-
Save albertywu/2e305815e36f30eca0c75dc1aca44e07 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ProfitCalculator { | |
| constructor(prices) { | |
| this.prices = prices | |
| } | |
| // implementation 1 uses standard for-loop | |
| getMaxProfit() { | |
| let maxProfit = 0 | |
| let minPrice = this.prices[0] | |
| for (let i = 0; i < this.prices.length; i++) { | |
| minPrice = Math.min(minPrice, this.prices[i]) | |
| maxProfit = Math.max(maxProfit, (this.prices[i] - minPrice)) | |
| } | |
| return maxProfit | |
| } | |
| // implementation 2 uses functional-style (no variables, no loops) | |
| getMaxProfitFunctional() { | |
| return this.prices.reduce((acc, curr) => ({ | |
| minPrice: Math.min(acc.minPrice, curr), | |
| maxProfit: Math.max(acc.maxProfit, curr - Math.min(acc.minPrice, curr)) | |
| }), { | |
| minPrice: this.prices[0], | |
| maxProfit: 0 | |
| }).maxProfit | |
| } | |
| } | |
| const calc = new ProfitCalculator([ | |
| 0.5, | |
| 50, | |
| 25.3, | |
| 100, | |
| 101, | |
| 1000, | |
| 42 | |
| ]) | |
| console.log( | |
| calc.getMaxProfit(), | |
| calc.getMaxProfitFunctional() | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment