1

I see that processingjs (p5.js) uses map() to normalise a number from one range into another range. What do I do if I want to map a function across a list? In js, python, Haskell, scheme etc etc, I’d use map(fn, list)... I’ve tried to find this discussed - apologies if it’s an FAQ,

And thanks

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
user2162871
  • 409
  • 3
  • 10
  • Note that processing.js and p5js are completely different projects. The former was discontinued in December 2018. As for `map`, numerical range mapping has nothing to do with mapping a function over a list: look at the specific list datatype if that's what you need to do, for its API. – Mike 'Pomax' Kamermans Dec 26 '19 at 14:28
  • @Mike'Pomax'Kamermans thanks MIke - my question was around p5js defining its map to do something quite different from map(fn, array). Cleared up when I was reminded that the js syntax is array.map(fn). I wonder if p5js could have used a better name for its “map”. And thanks for the heads up re processingjs. – user2162871 Dec 26 '19 at 22:59
  • Better name? Map does exactly what the people who Processing/p5js is intended for would expect it to do. In this the graphical programming context, calling the mapping of a function over a list `map` is the odd one out: that should have been `apply`, but then again that already existed for rather different purposes. The normal approach is to namespace functions with the same name, which is still the case: for graphics, all the "mathy" things are kept global, rather than tucked under `Math` or the like, while everything else is kept where it belongs as per Java(ish) convention. – Mike 'Pomax' Kamermans Dec 27 '19 at 16:00

1 Answers1

2

In JavasScript, the .map() function is part of the array prototype, this allows you to call map() on the array. So the syntax will be simply:

arr.map(fn)

Example:

const arr = [1, 2, 3, 4];
const res = arr.map(x => x*10);
console.log(res); // [10, 20, 30, 40]
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

In p5.js, the map() method is added to the global window, which means calling map() by itself is different from calling it as a property of the array:

function setup() {
  console.log('map' in window);
  const value = 50;
  console.log(map(value, 0, 100, 0, 200)); // 100
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64