Skip to content

Instantly share code, notes, and snippets.

@albertywu
Created January 19, 2017 16:11
Show Gist options
  • Select an option

  • Save albertywu/2e305815e36f30eca0c75dc1aca44e07 to your computer and use it in GitHub Desktop.

Select an option

Save albertywu/2e305815e36f30eca0c75dc1aca44e07 to your computer and use it in GitHub Desktop.
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