aboutsummaryrefslogtreecommitdiff
path: root/space.js
blob: d7f68e8ad967ee28d88b9c622a6a4634bdd4ea5a (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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// space.js, a full (not sparse data storage object) with some utilities.
// This includes from/to fetch, write, files, and ad-hoc strings. [DONE] [DONE] [DONE] [DONE] [DONE]
// It provides combination between Spaces. [DONE]
// It also gives a search utility and a utility to grab an arbitrary section [DONE] [DONE]
const fs = require('fs')
const vec = require('./utils/vec');

function chop(string, n){ // chops a string into n-sized chunks. Assumed to be perfect multiple
  let arr = [];
  for (let sec = 0; sec < string.length; sec++){
    arr.push(string.slice(sec*n,(sec+1)*n));
  }
  return arr;
}

function replace(text, old, repl){ //replaces, in an array `text`, the instances of `old` with `repl`
  for (let i=0; i<text.length; i++){
    if (text[i] == old) text[i] = repl;
  }
  return text;
}

function Space(){
  this.data = [];
  this.loc = []; // Coordinates to represent topleft location of spaces, and aid with .comb
  this.fromfetch = function(tiles, dimension, conform=true){ //tiles is straight from fetch/tileUpdate function, dimension is a min/max pair of y/x coordinates; conform is false for tileUpdate because the cell_props don't actually mean anything; all data is still included
    this.loc = vec.tileToChar(dimension[0]);
    for (let y=dimension[0][0]; y<=dimension[1][0]; y++){
      for (let line=0; line<8; line++)
        this.data.push([]); // Adds lines
      for (let x=dimension[0][1]; x<=dimension[1][1]; x++){
        if (! tiles[[y,x]]) tilein({"content":' '.repeat(16*8),"properties":{"cell_props":{}}}); // Insert a null tile if server sends null
        else tilein.call(this, tiles[[y,x]], y-dimension[0][0]);
      }
    }

    function tilein(tile, tilerow){ //tile is one of the tiles from `tiles`, and tilerow is y-dimension[0]; helper function
      let incl = Object.keys(tile.properties.cell_props).map(linenum => parseInt(linenum)) // list of included lines in the content
      let cont = chop(tile.content,16);
      let read = 0; //line of cont to read
      for (let line=0; line<8; line++){
        curline = line+8*tilerow;
        if (conform && incl.includes(line)){
          for (let i=0; i<16; i++) this.data[curline].push(' ');
        } else {
          this.data[curline].push(...cont[read]);
          read++;
        }
      }
    }
  }

  this.towrite = function(){ // Does no splitting or anything like that. Just returns a list of triplets for the write function
    let writes = [];
    for (let line = 0; line < this.data.length; line++) for (let chr = 0; chr < this.data[line].length; chr++){
      if (this.data[line][chr] == '') continue; // Internal coding for "do not write"
      writes.push([[this.loc[0]+line, this.loc[1]+chr],this.data[line][chr]]);
    }
    return writes;
  }

  this.tofile = function(filename){
    fs.writeFileSync(filename, this.print());
  };
  
  this.print = function(){
    return this.data.map(row => replace(replace(replace(row.slice(),'&','\\&'),'\\','\\\\'),'','&').join('')).join('\n');
  }

  this.fromfile = function(filename){ //Reads an external file into internal data
    this.adhoc(fs.readFileSync(filename,'utf8'));
  }

  this.adhoc = function(text){
    text = text.split('\n')
    text = text.map(row => row.split(''));
    this.data = text.map(row => {
      for (let i = 0; i<row.length; i++){
        if (row[i] == '\\') row.splice(i,1);
        else if (row[i] == '&') row[i] = '';
      }
      return row;
    });
  }

  this.comb = function(other, func){ // other must have a valid .loc. If this.loc null, treated as offset
    if (! other.loc) throw "The secondary space must have a valid .loc"
    if (this.loc.length == 0) {
      offset = [0, 0];
      this.loc = other.loc;
    } else {
      offset = vec.sub(this.loc, other.loc);
      if (this.data.length > 0)
        this.loc = vec.elem(this.loc, other.loc, (a,b) => Math.min(a,b));
    } // offset is position of other relative to this, so these are mainly definitional.
    // Convert negative offsets of either sort into zero offsets with significant previous whitespace (translation)
    for (let i = 0; i < -offset[0]; i++) this.data.unshift([]);
    if (offset[0] < 0) offset[0] = 0;
    for (let row = 0; row < this.data.length; row++){ // offset[1] < 0 fix
      for (let i = 0; i < -offset[1]; i++) this.data[row].unshift('');
    }
    if (offset[1] < 0) offset[1] = 0;

    // Parse over all relevant tiles and process them into usable chars (this.data is all relevant tiles due to padding)
    while (this.data.length < offset[0]+other.data.length) this.data.push([]); // Row padding
    for (let row = 0; row < this.data.length; row++){
      let otherrow = other.data[row-offset[0]] || [];
      while (this.data[row].length < offset[1]+otherrow.length) this.data[row].push(''); // Character-wise padding
      for (let chr = 0; chr < this.data[row].length; chr++){
        this.data[row][chr] = func(this.data[row][chr], otherrow[chr-offset[1]] || '');
      }
    }
  }

  this.search = function(other){ //Returns first instance of `other` subspace (prioritized vertically then horizontally)
    // Non-standard exclusion of this.loc
    let loc = [];
    for (let line=0; line<=this.data.length-other.data.length; line++){ for (let chr=0; chr<=this.data[line].length-other.data[0].length; chr++){
      var match = true;
      for (let y=0; y<other.data.length; y++) for (let x=0; x<other.data[y].length; x++){
        if (this.data[line+y][chr+x] != other.data[y][x]){
          match = false;
          break;
        }
      }
      if (match){
        loc = [line,chr];
        break;
      }
    } if (match) break;}
    return loc;
  }

  this.subsection = function(range){ // range is a coordinate pair
    // Similarly excludes this.loc
    newspace = new Space();
    for (let line=range[0][0]; line<range[1][0]; line++){
      newspace.data.push([]);
      let thisline = this.data[line] || [];
      for (let chr=range[0][1]; chr<range[1][1]; chr++){
        newspace.data[line-range[0][0]].push(thisline[chr] || '');
      }
    }
    return newspace;
  }

  this.copy = function(){ // deeply copies `array` and `loc` to a new space
    let newspace = new Space();
    newspace.data = this.data.map(row => row.slice()); // Deep copy
    newspace.loc = this.loc.slice();
    return newspace;
  }
}
    
module.exports = Space