Get Programming with JavaScript - Listing 7.04

Listing 7.04 - Moving a point in 2D

var point1; var point2; var move; var showPoint; move = function (point, change) { return { x: point.x + change.x, y: point.y + change.y }; }; showPoint = function (point) { console.log("( " + point.x + " , " + point.y + " )"); }; point1 = { x : 2, y : 5 }; point2 = move(point1, { x : 4, y : -2 }); showPoint(point1); console.log("Move 4 across and 2 down"); showPoint(point2);

Further Adventures

Listing 7.04 - Moving a point in 2D - Task 1

var point1; var point2; var move; var showPoint; move = function (point, change) { return { x: point.x + change.x, y: point.y + change.y }; }; showPoint = function (point) { console.log("( " + point.x + " , " + point.y + " )"); }; point1 = { x : 2, y : 5 }; // the second argument specifies the movement point2 = move(point1, { x : 7, y : 5 }); showPoint(point1); console.log("Move 7 across and 5 up"); showPoint(point2);

Listing 7.04 - Moving a point in 2D - Task 2

var point1; var point2; var reflectX; var showPoint; // define the new function and // assign it to a variable reflectX = function (point) { return { x: point.x, y: -point.y }; }; showPoint = function (point) { console.log("( " + point.x + " , " + point.y + " )"); }; point1 = { x : 2, y : 5 }; point2 = reflectX(point1); showPoint(point1); console.log("Reflect in the x-axis"); showPoint(point2);

When a point is reflected in the x-axis, its y-coordinate changes sign. i.e. 5 becomes -5 and -2 becomes 2.

Listing 7.04 - Moving a point in 2D - Task 3

var point1; var point2; var rotate90; var showPoint; // define the new function and // assign it to a variable rotate90 = function (point) { return { x: -point.y, y: point.x }; }; showPoint = function (point) { console.log("( " + point.x + " , " + point.y + " )"); }; point1 = { x : 2, y : 5 }; point2 = rotate90(point1); showPoint(point1); console.log("Rotate 90 degrees anticlockwise about (0, 0)"); showPoint(point2);

It can help to draw a sketch of a simple object being rotated.

The new x-coordinate is -1 × the old y-coordinate.

The new y-coordinate is the same as the old x-coordinate.