diff options
author | toasted-nutbread <toasted-nutbread@users.noreply.github.com> | 2022-08-20 11:31:06 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-08-20 11:31:06 -0400 |
commit | 9436928e3d89110d042e39067f5591c48e8500ea (patch) | |
tree | 3bf71caac36d64aa6769785a5c771c5678d8992f /ext | |
parent | 5dcb698a5add9cf43665db1aee38aca642041247 (diff) |
Optimize AnkiConnect.findNoteIds (#2190)
* Use for loop rather than map
* Add _getNoteQuery
* Optimize findNoteIds to reduce repeat queries
Diffstat (limited to 'ext')
-rw-r--r-- | ext/js/comm/anki-connect.js | 56 |
1 files changed, 43 insertions, 13 deletions
diff --git a/ext/js/comm/anki-connect.js b/ext/js/comm/anki-connect.js index f0aff8fa..9e3bd871 100644 --- a/ext/js/comm/anki-connect.js +++ b/ext/js/comm/anki-connect.js @@ -153,20 +153,36 @@ class AnkiConnect { async findNoteIds(notes) { if (!this._enabled) { return []; } await this._checkVersion(); - const actions = notes.map((note) => { - let query = ''; - switch (this._getDuplicateScopeFromNote(note)) { - case 'deck': - query = `"deck:${this._escapeQuery(note.deckName)}" `; - break; - case 'deck-root': - query = `"deck:${this._escapeQuery(AnkiUtil.getRootDeckName(note.deckName))}" `; - break; + + const actions = []; + const actionsTargetsList = []; + const actionsTargetsMap = new Map(); + const allNoteIds = []; + + for (const note of notes) { + const query = this._getNoteQuery(note); + let actionsTargets = actionsTargetsMap.get(query); + if (typeof actionsTargets === 'undefined') { + actionsTargets = []; + actionsTargetsList.push(actionsTargets); + actionsTargetsMap.set(query, actionsTargets); + actions.push({action: 'findNotes', params: {query}}); + } + const noteIds = []; + allNoteIds.push(noteIds); + actionsTargets.push(noteIds); + } + + const result = await this._invoke('multi', {actions}); + for (let i = 0, ii = Math.min(result.length, actionsTargetsList.length); i < ii; ++i) { + const noteIds = result[i]; + for (const actionsTargets of actionsTargetsList[i]) { + for (const noteId of noteIds) { + actionsTargets.push(noteId); + } } - query += this._fieldsToQuery(note.fields); - return {action: 'findNotes', params: {query}}; - }); - return await this._invoke('multi', {actions}); + } + return allNoteIds; } async suspendCards(cardIds) { @@ -314,4 +330,18 @@ class AnkiConnect { } return null; } + + _getNoteQuery(note) { + let query = ''; + switch (this._getDuplicateScopeFromNote(note)) { + case 'deck': + query = `"deck:${this._escapeQuery(note.deckName)}" `; + break; + case 'deck-root': + query = `"deck:${this._escapeQuery(AnkiUtil.getRootDeckName(note.deckName))}" `; + break; + } + query += this._fieldsToQuery(note.fields); + return query; + } } |