0

I am trying to dynamically use the previous property's value for calculation of next property. I have a function like this in Typescript:

MacroGenerator(calories) {
  this.caloriedata['macroarray'] = [
    { 
      name: 'Low Carb, High Fat',
      pmacro: (Math.round(calories*220.46226218100)/100),
      pcals: (4*this.caloriedata['macroarray'][0].pmacro), // THIS IS HOW I TRIED ACCESSING THE PROPERTY AND GETTING ERROR
      fcals: (calories*0.3),
      fmacro: (Math.round(this.caloriedata['macroarray'][0].fcals/9)/100),
      ccals: (calories-this.caloriedata['macroarray'][0].pcals-this.caloriedata['macroarray'][0].fcals),
      cmacro: (Math.round(this.caloriedata['macroarray'][0].ccals/4)/100),
    }
  ]
}

I suppose the object isn't instantiated as of when I am trying to access. Is there any way to access it?

Ayush Singh
  • 306
  • 1
  • 4
  • 12
  • Do you write the workout / nutrition app for yourself or is this going to be a commercial product? Do you plan to open source the code? – baao Jun 26 '18 at 18:32
  • It is going to be a website for my upcoming Youtube channel :) Code is open source on my git @ayush013 – Ayush Singh Jun 26 '18 at 18:34

1 Answers1

3

You can use Javascript Getters

From MDN

Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter

var obj = {
  a: 4,
  get b() {
    return this.a * 2;
  }
}

console.log(obj.b)
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35