Use Map for Mecab.listeners

This commit is contained in:
toasted-nutbread 2020-01-24 22:02:53 -05:00
parent 632765a3b5
commit d7ce829107

View File

@ -20,7 +20,7 @@
class Mecab { class Mecab {
constructor() { constructor() {
this.port = null; this.port = null;
this.listeners = {}; this.listeners = new Map();
this.sequence = 0; this.sequence = 0;
} }
@ -55,17 +55,18 @@ class Mecab {
if (this.port === null) { return; } if (this.port === null) { return; }
this.port.disconnect(); this.port.disconnect();
this.port = null; this.port = null;
this.listeners = {}; this.listeners.clear();
this.sequence = 0; this.sequence = 0;
} }
onNativeMessage({sequence, data}) { onNativeMessage({sequence, data}) {
if (hasOwn(this.listeners, sequence)) { const listener = this.listeners.get(sequence);
const {callback, timer} = this.listeners[sequence]; if (typeof listener === 'undefined') { return; }
clearTimeout(timer);
callback(data); const {callback, timer} = listener;
delete this.listeners[sequence]; clearTimeout(timer);
} callback(data);
this.listeners.delete(sequence);
} }
invoke(action, params) { invoke(action, params) {
@ -75,13 +76,13 @@ class Mecab {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const sequence = this.sequence++; const sequence = this.sequence++;
this.listeners[sequence] = { this.listeners.set(sequence, {
callback: resolve, callback: resolve,
timer: setTimeout(() => { timer: setTimeout(() => {
delete this.listeners[sequence]; this.listeners.delete(sequence);
reject(new Error(`Mecab invoke timed out in ${Mecab.timeout} ms`)); reject(new Error(`Mecab invoke timed out in ${Mecab.timeout} ms`));
}, Mecab.timeout) }, Mecab.timeout)
}; });
this.port.postMessage({action, params, sequence}); this.port.postMessage({action, params, sequence});
}); });