aboutsummaryrefslogtreecommitdiff
path: root/utils/vec.js
blob: 4e65abd3c5f50b6dfb222084e9d2a05620b7ea6b (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
43
44
45
// 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){
  if (orig.length > vec.length) throw "Vector length mismatch";
  if (orig.length && isNaN(orig[0])) throw "orig vec has a NaN";
  if (vec.length && isNaN(vec[0])) throw "new vec has a NaN";
  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.dot(orig, [1/8, 1/16]).map(a => Math.floor(a));
}
exports.norm = function(orig){
  let sum = orig.reduce( (acc, cur) => acc+cur );
  return exports.dot(orig, 1/sum);
}