-1

I have Currency Class at currency.js file and i have main.js file

In currency.js I want to use getExchangeRate() function with 2 parameters (currency1, currency2) and then I want to bind this function to convert(amount) method. I dont want to give currency1 and currency2 params to convert method again. Then I want to use convert method in main.js like this convert(currency1, currency2, amount) but it doesnt work.

class Currency{
    constructor(){
        
    }

    async getExchangeRate(currency1 , currency2){
        this.currency1=currency1;
        this.currency2 = currency2
        this.url = `https://api.exchangerate.host/convert?from=${currency1}&to=${currency2}`
        
        const excResponse = await fetch(this.url)
        const excResponseJSON = await excResponse.json()
        return excResponseJSON.result 
    }

   async convert(amount){
    this.amount = amount;
    let value1 = await this.getExchangeRate(currency1 , currency2)
    
    return value1 * amount;
   }
 
}

main.js

currency.convert("USD", "EUR", 3)
.then(response => console.log(response))
.catch(err => console.log(err))

pilchard
  • 12,414
  • 5
  • 11
  • 23
Furkan
  • 3
  • 5
  • why would you expect it to work? `convert()` only accepts a single parameter (`amount`) but you are passing 3. – pilchard Jun 19 '22 at 20:35
  • i want to bind getExchangeRate() with convert(). So First two param at convert will be getExchangeRate() 's params nad third param is convert()'s param. – Furkan Jun 19 '22 at 20:38
  • The you either need to handle it in the `constructor`, create a [curried](https://stackoverflow.com/questions/36314/what-is-currying) method, or accept all three parameters. – pilchard Jun 19 '22 at 20:41
  • "*I want to use the method in main.js like `convert(currency1, currency2, amount)`*" and "*I dont want to give `currency1` and `currency2` params to `convert` method*" are exact opposites. You can have only one of them. So what do you really want? – Bergi Jun 19 '22 at 23:48
  • Btw, there is no good reason to assign `currency1`, `currency2`, `url` or `amount` properties on your instance. In fact, there's not even a good reason to use a `class Currency`, the `convert` and `getExchangeRate` functions should be simple standalone functions. – Bergi Jun 19 '22 at 23:52

1 Answers1

0

as @pilchard said, a curried method can "remember" the parameters bcz it returns a scoped function. Maybe something like this?

async getExchangeRate(currency1, currency2) {
    
    // ...

    return function(amount) {
        return excResponseJSON.result * amount
    }
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28