Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Last active August 29, 2015 14:01
Show Gist options
  • Save kl0tl/a22b81dc8b1baded7aad to your computer and use it in GitHub Desktop.
Save kl0tl/a22b81dc8b1baded7aad to your computer and use it in GitHub Desktop.
Swizzle operator for the awesome https://github.com/toji/gl-matrix
var $each, $every, aliases;
$each = Function.prototype.call.bind(Array.prototype.forEach);
$every = Function.prototype.call.bind(Array.prototype.every);
aliases = {
x: 'r', y: 'g', z: 'b', w: 'a'
};
function f(dest, channels, aliases) {
$each(channels, (channel, index) => {
dest[channel] = (vec) => vec[index];
if (aliases) dest[aliases[channel]] = dest[channel];
});
return dest;
}
function proxify(target) {
return new Proxy(target, {
get: (target, channels) => {
if (channels.length < 2 || channels.length > 4) {
return target[channels];
}
if (channels in proxify.cache) {
return proxify.cache[channels];
}
if (!$every(channels, (channel) => channel in target)) {
return target[channels];
}
return (proxify.cache[channels] = function (vec) {
var output, context;
output = new vec.constructor(channels.length);
context = this || target;
$each(channels, (channel, index) => {
output[index] = context[channel](vec);
});
return output;
});
}
});
}
proxify.cache = {
__proto__: null
};
vec2 = proxify(f(vec2, 'xy'));
vec3 = proxify(f(vec3, 'xyz', aliases));
vec4 = proxify(f(vec4, 'xyzw', aliases));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment