# The map() method creates a new array with the results of calling a provided function on every element

• Hi,

can p.map() be used to translate, scale or rotate points in an array with the corresponding function?

For now I use something like this, but prefer to use . map.

Any suggestion how to use .map to do the job?

``````// small triangle
var p = [0,0,0,50,50,50];

function translate(tx, ty, p) {
p.forEach((e, i) => {
p[i] += (i % 2) ? ty : tx;
});
return p;
}

function scale(sx, sy, p) {
p.forEach((e, i) => {
p[i] *= (i % 2) ? sy : sx;
});
return p;
}

g.clear();
g.drawPoly(p,1);
g.drawPoly(translate(50,0,p.slice()),1);­
g.drawPoly(translate(50,50,scale(2,2,p.s­lice())),1);

``````
• ``````var p = [0,0,0,50,50,50];

function translate(tx, ty, p) {
return p.map((x, i)=> x+((i%2)?ty:tx));
}
function scale(sx, sy, p) {
return p.map((x, i) => x*((i % 2) ? sy : sx));
}
g.clear();
g.drawPoly(p,1);
g.drawPoly(translate(50,0,p.slice()),1);­
g.drawPoly(translate(50,50,scale(2,2,p.s­lice())),1);

``````

Keep in mind that this allocates a new array every time. Easier to reason about IMO, but don't allocate a lot, if you are low on memory.

And of course you can do it in a one-liner:

``````var translate = (tx, ty, p) => p.map((x, i)=> x + ((i % 2) ? ty : tx));
var scale = (sx, sy, p) => p.map((x, i) => x * ((i % 2) ? sy : sx));
``````