Home > OS >  How to update (closure) so that it keeps updating
How to update (closure) so that it keeps updating

Time:07-22

So in this code, what I have to do is, I want to set my ROIto 8% initially, and changes so on

It has to be done with closure concept. I got confused here and tried very much before asking for the help.

 if (Math.random() > 0.5) {
  const x = 1;
} else {
  const x = 2;
}
console.log(x);

Believe me, I tried so much before asking for the help. Please help me to correct this.

CodePudding user response:

If I understand correctly you want to be able to update the rate of interest while externally to the calculating function. Instead of using global variable we use closure. However, since there are 2 functions involved I return them in an object.

const createLoanCalculator = (rateOfInterest, principle, term) => {

  var installment = 1; // ?
  var _rateOfInterest = rateOfInterest;

  const updatedRateOfInterest = (x) => {
    _rateOfInterest = x;
  }

  const simpleInterest = (principle, term) => {
    simpleInterestValue = _rateOfInterest * principle * installment / 100;
    return simpleInterestValue;
  }

  return {
    updatedRateOfInterest,
    simpleInterest
  };
}
const obj_calculator = createLoanCalculator(8, 4000, 6);
var simpleInterest = obj_calculator.simpleInterest
var updatedRateOfInterest = obj_calculator.updatedRateOfInterest

console.log(simpleInterest(200, 30));
updatedRateOfInterest(12)
console.log(simpleInterest(200, 30));

  • Related