Let's Play with JS Array Objects (in ExtendScript)
September 14, 2024 | Tips | en | fr
IdExtenso provides a new ArrayAs2D
module that unleashes the hidden strengths of ExtendScript operators. With this toy, you can now write code that adds, multiplies, evaluates 2D points or vectors. For example, if you develop an InDesign script based on Bézier curves or working on polygonal paths, all calculations of points, distances, normalized vectors, etc. become wonderfully compact…
To give you a taste of the joy of working with $$.ArrayAs2D, here is a randomly written example of perfectly valid code:
// Given `myPathPoint` a valid PathPoint instance. var A = myPathPoint.anchor; // Some points... var P = A + [3,5]; var Q = -P + A + [7,8]/3; // ...or vectors var U = 1.25 * (A - myPathPoint.leftDirection); var V = Q + (myPathPoint.rightDirection - A); if( U > 3 ) // if |U| is greater than 3... V += U; else V *= 4;
Whenever an Array
happens to have two numeric coordinates x,y, it automatically benefits from so-called overloaded operators which give meaning to addition or subtraction, multiplication or division by a scalar, and so on.
Natively, JavaScript won't be able to interpret the code [3,2] + 5*[6,7]
, but with ExtendScript we can make it fully functional. The gain is considerable: no intermediate variables, no separate calculations “along x” and “along y” to finally reconcile coordinates in a new object.
If your project involves fairly complex vector operations, condensing the fundamental calculations is a game changer. With $$.ArrayAs2D, not only can you sum or multiply points and/or vectors directly, but many other shortcuts are available:
• +[3,4]
returns the norm of the vector (i.e. 5.)
• The distance between two points P and Q is simply written P|Q
.
• If you want to save the square root, you can also write P^Q
to get the square of the distance.
• U>>V
— read “U to V” — yields the (signed) angle between these two vectors.
Note. — But if the second operand is a number α, then U>>α
rotates the vector U by α radians; example: [2,3]>>Math.PI
.
• 1/U
returns the normalized vector U/|U|, so we have the equality 1 == +(1/U)
.
• Point (or vector) equality is also testable (U==V
), relying on your own machine-epsilon, if the default is not suitable.
All you have to do is #include
this small module (very light weight) in your IdExtenso script. It can be activated or deactivated on demand. Read its detailed instructions and enter a new… dimension!
→ ArrayAs2D module (IdExtenso)
→ See also “Operator Overloading with ExtendScript”