December 28th, 2009 at 5:46 am

My new favorite function: map

Jump to Comments
Submit to del.icio.us

Map, that’s my new favorite pure function. It’s very simple in use and has tons of uses! Ever been fidgeting with numbers trying to get the right output? Save your time the next time and use Map!

1
2
3
4
function map($v, $a, $b, $x = 0, $y = 1)
{
  return ($v == $a) ? $x : ($v - $a) * ($y - $x) / ($b - $a) + $x;
}

As you can see it’s very easy in use. The first parameter is the value that needs to be mapped, the next two values are respectfully the minimum and maximum value of the input and the last two are respectfully the min and max of the output.

So lets take an example: It’s 20 degrees Celsius outside, but we want to map it to Fahrenheit.

1
map($_GET['c'], -40, 200, -40, 392);

And that’s it!, we know that -40 degrees Celsius is -40 degrees Fahrenheit and that 200 degrees Celsius is 392 degrees Fahrenheit, and this way the value of c gets mapped from Celsius to Fahrenheit, that simple! No more fidgeting with formulae.

Also because it’s a pure function it’s easily memoized, this will make the already fast function even faster by caching the inputs and the outputs. But because I don’t know an easy way of Memoizing functions in PHP except for explicitly making the function memoized, i’ll leave it with a link to Wikipedia.

Leave a Reply

Bear