Skip to content

Instantly share code, notes, and snippets.

@olchyk98
Created July 12, 2025 15:43
Show Gist options
  • Select an option

  • Save olchyk98/68412332d6f3d3e341019847ff324a5f to your computer and use it in GitHub Desktop.

Select an option

Save olchyk98/68412332d6f3d3e341019847ff324a5f to your computer and use it in GitHub Desktop.
GLSL Vector Swizzling in Javascript
function vec(...args) {
if (args.length > 4) {
throw new Error('Only vectors with up to 4 elements are supported.')
}
const proxied = new Proxy(args, {
get(t, p) {
if (['x', 'r'].includes(p)) return t[0]
if (['y', 'g'].includes(p)) return t[1]
if (['z', 'b'].includes(p)) return t[2]
if (['w', 'a'].includes(p)) return t[3]
if (p.length <= 1) return t[p]
const ingredients = p
.split('')
.map((i) => proxied[i])
if (ingredients.every(Boolean)) {
return vec(...ingredients)
}
return t[p]
},
set(t, p, v) {
t[p] = v
return true
}
})
return proxied
}
const vec4 = (a, b, c, d) => vec(a, b, c, d)
const vec3 = (a, b, c) => vec(a, b, c)
const vec2 = (a, b) => vec(a, b)
const vec1 = (a) => vec(a)
const v4 = vec4(1, 2, 3, 4)
// Swizzling
console.log(v4.rgba.abgr.xya.yx) // [3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment