Optimize AnkiConnect.findNoteIds (#2190)

* Use for loop rather than map

* Add _getNoteQuery

* Optimize findNoteIds to reduce repeat queries
This commit is contained in:
toasted-nutbread 2022-08-20 11:31:06 -04:00 committed by GitHub
parent 5dcb698a5a
commit 9436928e3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -153,20 +153,36 @@ class AnkiConnect {
async findNoteIds(notes) { async findNoteIds(notes) {
if (!this._enabled) { return []; } if (!this._enabled) { return []; }
await this._checkVersion(); await this._checkVersion();
const actions = notes.map((note) => {
let query = ''; const actions = [];
switch (this._getDuplicateScopeFromNote(note)) { const actionsTargetsList = [];
case 'deck': const actionsTargetsMap = new Map();
query = `"deck:${this._escapeQuery(note.deckName)}" `; const allNoteIds = [];
break;
case 'deck-root': for (const note of notes) {
query = `"deck:${this._escapeQuery(AnkiUtil.getRootDeckName(note.deckName))}" `; const query = this._getNoteQuery(note);
break; let actionsTargets = actionsTargetsMap.get(query);
if (typeof actionsTargets === 'undefined') {
actionsTargets = [];
actionsTargetsList.push(actionsTargets);
actionsTargetsMap.set(query, actionsTargets);
actions.push({action: 'findNotes', params: {query}});
} }
query += this._fieldsToQuery(note.fields); const noteIds = [];
return {action: 'findNotes', params: {query}}; allNoteIds.push(noteIds);
}); actionsTargets.push(noteIds);
return await this._invoke('multi', {actions}); }
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);
}
}
}
return allNoteIds;
} }
async suspendCards(cardIds) { async suspendCards(cardIds) {
@ -314,4 +330,18 @@ class AnkiConnect {
} }
return null; 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;
}
} }