Skip to content

Instantly share code, notes, and snippets.

@Traineratwot
Last active February 5, 2024 08:24
Show Gist options
  • Save Traineratwot/64d03cf20f1a90124e1274dbbdec386d to your computer and use it in GitHub Desktop.
Save Traineratwot/64d03cf20f1a90124e1274dbbdec386d to your computer and use it in GitHub Desktop.
Функция подобия
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