I have 2 arrays: [-26, -5] [-5.3, 2.3], and a percentage value from 0 to 100 that changes on scroll.
I need a function that generates a number by percentage between two numbers, where percentage 0 is the first value from the array, and where 100 percent is the second value. 50% is exactly in the middle of the two numbers. After receiving a number, reduce it to hundredths.
For example:
const result1 = someMagick(50%, [-26, -5]);
const result2 = someMagick(100%, [-26, -5]);
console.log(result1, result2)
// -16, -26
I don’t have any thoughts how to do it, please help
>Solution :
function someMagick(percentage, numbers) {
// Convert percentage value to decimal
const decimalPercentage = percentage / 100;
// Calculate range between numbers
const range = numbers[1] - numbers[0];
// Calculate result by adding first number in array to the product of the percentage value and the range
const result = numbers[0] + (decimalPercentage * range);
// Return result rounded to the nearest hundredth
return Math.round(result * 100) / 100;
}
// Example usage
const result1 = someMagick(50, [-26, -5]);
const result2 = someMagick(100, [-26, -5]);
console.log(result1, result2);
// -16, -26
You can then use this function to generate a number by percentage between two numbers in your code.