Arduino map

A more visual representation of how the map function in Arduino works.

by Gradox

HTML

<div>
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/Arduino_Logo.svg/64px-Arduino_Logo.svg.png">
    
<h2>Arduino map function</h2>

</div>
<input type="range" id="slider" min="0" max="100" step="1" oninput="showValue(this.value)" />
<form>In_min :
    <input type="number" class="input" value="0">
    <br>In_max :
    <input type="number" class="input" value="100">
    <br>Out_min:
    <input type="number" class="input" value="0">
    <br>Out_max:
    <input type="number" class="input" value="200">
    <br>
</form>
<p id="value">50</p>
<p id="result">0</p>

CSS

body {
    font-family: monospace;
}
p {
    font-size: 2em;
}
img {
    vertical-align: middle;
}
h2 {
    display: inline;
}
form > input {
    width: 100px;
}
#value::before {
    content:"Input: ";
}
#result::before {
    content:"Output: ";
}
#slider {
    width: 300px;
}

JavaScript

const slider = document.getElementById("slider");
const value = document.getElementById("value");
const result = document.getElementById("result");
const inputElements = document.getElementsByClassName("input");

function showValue(newValue) {
    const data = [].map.call(inputElements, obj => parseInt(obj.value));

    if (data[0] > data[1]) {
        slider.setAttribute("min", data[1]); // in_max
        slider.setAttribute("max", data[0]); // in_min
        newValue = map(newValue, data[0], data[1], data[1], data[0]);
    } else {
        slider.setAttribute("min", data[0]); // in_min
        slider.setAttribute("max", data[1]); // in_max
    }
    value.innerHTML = newValue;
    result.innerHTML = map(newValue, data[0], data[1], data[2], data[3]);
}

function map(x, in_min, in_max, out_min, out_max) {
    return Math.floor((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
}