Skip to content

How to use a spread or map operator to apply this formula to an array of Uint16 pairs?

I’ve been trying to better understand the spread and/or map operator, specifically how to apply math using it.

I have an array of two Uint16 number pairs like this:

let randomPairs = [
  [ 37096, 65104 ], [ 62271, 3432 ],  [ 1191, 43320 ],  [ 5388, 16819 ],
  [ 52224, 52222 ], [ 61913, 48798 ], [ 52950, 18227 ], [ 23232, 43931 ],
  [ 14995, 45924 ], [ 20609, 46597 ], [ 2392, 52582 ],  [ 7050, 51498 ],
  [ 34253, 11210 ], [ 43376, 41964 ], [ 63238, 34740 ], [ 63254, 56620 ]
]

I would like to use the spread or map operator to apply the following formula to each pair. The formula combines the pair into Uint32, then converts it to a float between 0-1.

(((2**16) * u1) + u2) / ((2 ** 32) - 1)

Where u1 represents the first item in a pair, and u2 represents the second item in the pair.

I don’t really know how to do it at all, but here is my code that takes the array and applies the formula using a for loop:

let i,j,temparray,chunk = 2, u1, u2
for (i=0,j=randomPairs.length; i<j; i+=chunk) {

    temparray = randomPairs.slice(i,i+chunk);
    u1 = temparray[0]
    u2 = temparray[1]
    let float = (((2**16) * u1) + u2) / ((2 ** 32)  - 1)
    
    console.log(float)
}

How can I use a spread or map operator to convert the randomPairs array into an array of the desired floats for each pair?

If Float32Array() could be used somehow, I’m all ears about that as well.

Answer

If you want to apply an operation on each element in an array, you can use the map method:

let randomPairs = [
  [ 37096, 65104 ], [ 62271, 3432 ],  [ 1191, 43320 ],  [ 5388, 16819 ],
  [ 52224, 52222 ], [ 61913, 48798 ], [ 52950, 18227 ], [ 23232, 43931 ],
  [ 14995, 45924 ], [ 20609, 46597 ], [ 2392, 52582 ],  [ 7050, 51498 ],
  [ 34253, 11210 ], [ 43376, 41964 ], [ 63238, 34740 ], [ 63254, 56620 ]
]

let floats = randomPairs.map(p => {
    return (((2**16) * p[0]) + p[1]) / ((2 ** 32)  - 1);
});

console.log(floats);

Alternatively, you can use the forEach method if you just want to console.log the output and don’t need an array of the resulting float values.