Last active
February 5, 2024 08:24
-
-
Save Traineratwot/64d03cf20f1a90124e1274dbbdec386d to your computer and use it in GitHub Desktop.
Функция подобия
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mapNumberToRange(number, target, condition) { | |
const targetMin = Math.min(...target); | |
const targetMax = Math.max(...target); | |
const conditionMin = Math.min(...condition); | |
const conditionMax = Math.max(...condition); | |
if (number > conditionMax) number = conditionMax | |
if (number < conditionMin) number = conditionMin | |
const targetSize = target[1] - target[0]; | |
const conditionSize = condition[1] - condition[0]; | |
let mappedNumber = 0; | |
if (targetSize > 0 && conditionSize > 0) { | |
mappedNumber = Math.floor((number - condition[0]) * (targetSize / conditionSize) + target[0]); | |
} else if (targetSize < 0 && conditionSize > 0) { | |
mappedNumber = Math.floor((number - condition[0]) * (targetSize / Math.abs(conditionSize)) + target[0]); | |
} else if (targetSize > 0 && conditionSize < 0) { | |
mappedNumber = Math.floor((number - condition[0]) * (Math.abs(targetSize) / conditionSize) + target[0]); | |
} else if (targetSize < 0 && conditionSize < 0) { | |
mappedNumber = Math.floor((number - condition[0]) * (Math.abs(targetSize) / Math.abs(conditionSize)) + target[0]); | |
} | |
if (mappedNumber > targetMax) mappedNumber = targetMax | |
if (mappedNumber < targetMin) mappedNumber = targetMin | |
return Math.round(mappedNumber); | |
} | |
console.log(mapNumberToRange(0, [16, 5],[0, 1000])); // Вывод: 16 | |
console.log(mapNumberToRange(1000, [16, 5],[0, 1000])); // Вывод: 5 | |
console.log(mapNumberToRange(500, [16, 5],[0, 1000])); // Вывод: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment