29 Companion zmachine.js (8/28)
// Encode a word the way dictionary entries are stored.
encodeWord(zsciiCodes) {
const n = this.version <= 3 ? 6 : 9;
const out = [];
for (const z of zsciiCodes) {
if (out.length >= n) break;
const ch = this.zsciiToChar(z);
let i;
if ((i = this.alphabets[0].indexOf(ch)) >= 0) out.push(i + 6);
else if ((i = this.alphabets[1].indexOf(ch)) >= 0) out.push(4, i + 6);
else if ((i = this.alphabets[2].indexOf(ch, 2)) >= 0) out.push(5, i + 6);
else out.push(5, 6, (z >> 5) & 31, z & 31);
}
while (out.length < n) out.push(5);
out.length = n;
const bytes = [];
for (let i = 0; i < n; i += 3) {
let w = (out[i] << 10) | (out[i + 1] << 5) | out[i + 2];
if (i + 3 >= n) w |= 0x8000;
bytes.push(w >> 8, w & 0xff);
}
return bytes;
}
// ---------------------------------------------------------------- output
print(s) {
if (!s) return;
if (this.mem3.length) {
const top = this.mem3[this.mem3.length - 1];
for (const ch of s) {
this.mem[top.table + 2 + top.len++] = this.charToZscii(ch);
}
return;
}
if (!this.screenOn) return;
if (this.window === 1) this.printUpper(s);
else this.out.push(s);
}