Skip to content

Instantly share code, notes, and snippets.

@Adam-Vandervorst
Last active June 27, 2021 22:44
Show Gist options
  • Select an option

  • Save Adam-Vandervorst/5c1da4806aca1cdb205ebce99aeef448 to your computer and use it in GitHub Desktop.

Select an option

Save Adam-Vandervorst/5c1da4806aca1cdb205ebce99aeef448 to your computer and use it in GitHub Desktop.
How small can you get it without loosing functionality? Brings about fun abstractions.
Vector=(x,y,V=Vector,M=f=>V(f(x),f(y)),P=f=>v=>V(f(v.x,x),f(v.y,y)),C=c=>M(_=>c),I=v=>x*v.x+y*v.y,A=()=>Math.sqrt(I(V(x, y))))=>({
x:x,
y:y,
toString:()=>`Vector(${x}, ${y})`,
[Symbol.iterator]:()=>[x,y].values(),
fromPolar:(r,a)=>V(r*Math.cos(a),r*Math.sin(a)),
map:M,
partial:M,
const:C,
zero:()=>C(0),
unit:()=>C(1),
copy:()=>M(a=>a),
opposite:()=>M(a=>-a),
inverse:()=>M(a=>1/a),
multiply:n=>M(a=>n*a),
divide:n=>M(a=>x/a),
noisy:k=>M(a=>a+2*k*(Math.random()-.5)),
max:P(Math.max),
min:P(Math.min),
add:P((a,b)=>a+b),
sub:P((a,b)=>a-b),
pointwise:P((a,b)=>a*b),
inner:I,
outer:v=>[[x*v.x,x*v.y],[y*v.x,y*v.y]],
normal:()=>V(-y,x),
angle:()=>Math.atan2(y,x),
norm:()=>A(),
normalized:()=>M(a=>a/A()),
isFinite:()=>isFinite(x)&&isFinite(y),
isClose:(v,e=1e-4)=>P((a,b)=>a-b).norm()<e
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment