skip to Main Content

I have these 10 variables already declared and they each contain a float value.

Is there any way to apply the function toFixed(prec) with prec as the parameter to all these variables with a shorter code? Using an array or something like that?

x1 = x1.toFixed(prec);
x2 = x2.toFixed(prec);
y1 = y1.toFixed(prec);
y2 = y2.toFixed(prec);
a1 = a1.toFixed(prec);
a2 = a2.toFixed(prec);
b1 = b1.toFixed(prec);
b2 = b2.toFixed(prec);
c1 = c1.toFixed(prec);
c2 = c2.toFixed(prec);

2

Answers


  1. Yes, you should keep all these parameters in object (as associative array in other language), than you can simply loop that object.

    /**
    Replace this:
    x1=x1.toFixed(prec);
    x2=x2.toFixed(prec);
    y1=y1.toFixed(prec);
    y2=y2.toFixed(prec);
    a1=a1.toFixed(prec);
    a2=a2.toFixed(prec);
    b1=b1.toFixed(prec);
    b2=b2.toFixed(prec);
    c1=c1.toFixed(prec);
    c2=c2.toFixed(prec);
    
    with this:
    */
    
    let options = {
      x1: 1.0,
      x2: 2.0,
      x3: 3.0,
    }
    
    console.log('Before', options);
    
    for (const [key, value] of Object.entries(options)) {
      options[key] = value.toFixed(3);
    }
    
    console.log('After', options);
    Login or Signup to reply.
  2. Put the variables into an array, map it and destructure:

    [x1, x2, y1, y2, ...] = [x1, x2, y1, y2, ...].map(num => num.toFixed(prec));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search