A module for creating n-dimensional vector types that support swizzling.
Arrays. These arrays are fixed-length and accept only numbers as input, though they generally decay gracefully into regular
Arrays. For example, you're allowed to use
concat, and other
Array methods, and if the result is a valid
vec will be returned. Otherwise, you'll get back a standard
Array with the new elements. These are specifically overloaded methods, so experimental, custom, and rebound methods aren't guaranteed to work.
$ npm install vecn
Since they're the most common,
vec4 are already included:
const vec3 =let v =console
1 2 3
If you need to create your own vector type:
const vecn =const vec5 = vecnvar v =console
1 2 3 4 5
For a more in-depth description of available vector methods, see the documentation.
Swizzling is a technique used in GLSL that allows you to access a vector's components by name and build new vectors from them. It works the same here at arbitrary length. It's easiest to see in an example:
var v =vx // 1vy // 2vz // 3vw // 4vxx // vec2 [ 1, 1 ]vzy // vec2 [ 3, 2 ]vzywwxyyz // vec8 [ 3, 2, 4, 4, 1, 2, 2, 3 ]
We can also set values with swizzling.
var v =vxz = 4 5console
4 2 5
Swizzling only works for
vec4 (with plans to extend it with custom accessors).
When creating a new vecType, you are generating a new class. However, this class is hidden behind a function that creates the object for you and returns a Proxy. Therefore, the function returned by
vecn.getVecType is not a constructor. Since the
new keyword implies a
return this at the end of the function, but the function already returns, the existence of a
new before the function call has no effect. The following code explains the importance:
const vec2 = vecnvar v1 = // Valid constructionvar v2 = 1 2 // Also valid, but misleadingv1constructor === vec2 // false
Basically this allows for swizzling and lets me extend
Array without letting the user mess with the length.