UNPKG

baxterize

Version:

A dumb a library which will expand letters and numbers into spelled out versions and except it own output as an input to reverse the transform.

129 lines (104 loc) 2.45 kB
const say = require('say'); const maps = require('./maps'); class baxterize { constructor (options) { this._params = Object.assign({}, options); this._reverse = {}; this._reading = null; if (!this._params.map && !this._params.type) { this._setMapType('alpha'); } else if (this._params.type) { this._setMapType(this._params.type); } else if (this._params.map) { this._setMap(map); } } getTypes () { return Object.keys(maps); } setOption (option, value) { switch (option) { case 'type': this._setMapType(value); break; case 'map': this._setMap(value); break; default: this._params[option] = value; break; } } expand (i, out = this._out.bind(this)) { const output = []; if (typeof i == 'number') { i = String(i); } for (let k = 0, j = i.length; k < j; k++) { output.push(this._map[i.charAt(k).toLowerCase()] || i.charAt(k)); } return out(output.join('-')); } contract (i, out = this._out.bind(this)) { const output = []; const parts = i.split('-'); if (!Object.keys(this._reverse).length) { this._reverse = this._reverseMap(this._map); } parts.forEach((part) => { output.push(this._reverse[part]); }); return out(output.join('')); } _setMapType (mapType) { if (maps[mapType]) { this._setMap(maps[mapType]); } else { throw new Error(`${mapType} is not a supported format. This only supported formats are ${Object.keys(maps)}.`); } } _setMap (map) { this._map = map; this._reverse = {}; } _out (output) { if (this._params.speak) { this._read(output); } if (this._params.write) { this._write(output); } return output; } _reverseMap (map) { const reverse = {}; const keys = Object.keys(map); keys.forEach((key) => { reverse[map[key]] = key; }); return reverse; } _read (output, reader = say.speak, callback=() => {}) { if (this._reading) this.stopReading(); this._reading = reader(output, this._params.voice, 1.0, (err) => { if (err) { throw new Error(err); } callback(); }); } _write (output, writer = say.export, callback=() => {}) { const outfile = this._params.outfile || `baxter-${new Date().toString()}.wav`; writer(output, this._params.voice, 1.0, outfile, (err) => { if (err) { throw new Error(err); } callback(); }); } stopReading () { this._reading.stop(); this._reading = null; } } module.exports = baxterize;