aboutsummaryrefslogtreecommitdiff
path: root/utils/vec.js
blob: 57104df2b1d57dca3f48ca458d6b2e2b7eb60af6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// A utility library for vector (coordinate) operations.

exports.mult = function(vec, scal){
  for (let i = 0; i < vec.length; i++)
    vec[i] = scal*vec[i];
  return vec;
}

exports.elem = function(orig, vec, op){
  let comb = [];
  for (let i = 0; i < orig.length; i++){
    comb.push(op(vec[i],orig[i]));
  }
  return comb;
}

exports.equals = function(orig, vec){
  for (let i = 0; i < orig.length; i++){
    if (orig[i] != vec[i]) return false;
  }
  return true;
}

exports.add = function(orig, vec){
  return exports.elem(orig, vec, (a,b) => a+b);
}
exports.sub = function(orig, vec){
  return exports.elem(orig, vec, (a,b) => a-b);
}
exports.dot = function(orig,vec){
  return exports.elem(orig, vec, (a,b) => a*b);
}
exports.tileToChar = function(orig){
  return exports.dot(orig, [8,16]);
}
exports.charToTile = function(orig){
  return exports.elem(exports.dot(orig, [1/8, 1/16]), [], a => Math.floor(a));
}
exports.norm = function(orig){
  let sum = orig.reduce( (acc, cur) => acc+cur );
  return exports.dot(orig, 1/sum);
}