From e091c7ebe2f6780b6a88df313c9f20170a8e5c1c Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 2 Nov 2019 16:21:06 -0400 Subject: Add support for deleting individual dictionaries --- ext/bg/js/translator.js | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index 9d90136b..ff1d24f3 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -42,6 +42,11 @@ class Translator { await this.database.purge(); } + async deleteDictionary(dictionaryName) { + this.tagCache = {}; + await this.database.deleteDictionary(dictionaryName); + } + async findTermsGrouped(text, dictionaries, alphanumeric, options) { const titles = Object.keys(dictionaries); const {length, definitions} = await this.findTerms(text, dictionaries, alphanumeric); -- cgit v1.2.3 From a9ab774a3fa4a1f161771b1291d1a8e4c5845084 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 4 Nov 2019 19:35:57 -0500 Subject: Move function --- ext/bg/js/translator.js | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index ff1d24f3..d04b1cb3 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -47,22 +47,6 @@ class Translator { await this.database.deleteDictionary(dictionaryName); } - async findTermsGrouped(text, dictionaries, alphanumeric, options) { - const titles = Object.keys(dictionaries); - const {length, definitions} = await this.findTerms(text, dictionaries, alphanumeric); - - const definitionsGrouped = dictTermsGroup(definitions, dictionaries); - await this.buildTermFrequencies(definitionsGrouped, titles); - - if (options.general.compactTags) { - for (const definition of definitionsGrouped) { - dictTermsCompressTags(definition.definitions); - } - } - - return {length, definitions: definitionsGrouped}; - } - async getSequencedDefinitions(definitions, mainDictionary) { const definitionsBySequence = dictTermsMergeBySequence(definitions, mainDictionary); const defaultDefinitions = definitionsBySequence['-1']; @@ -157,6 +141,22 @@ class Translator { return result; } + async findTermsGrouped(text, dictionaries, alphanumeric, options) { + const titles = Object.keys(dictionaries); + const {length, definitions} = await this.findTerms(text, dictionaries, alphanumeric); + + const definitionsGrouped = dictTermsGroup(definitions, dictionaries); + await this.buildTermFrequencies(definitionsGrouped, titles); + + if (options.general.compactTags) { + for (const definition of definitionsGrouped) { + dictTermsCompressTags(definition.definitions); + } + } + + return {length, definitions: definitionsGrouped}; + } + async findTermsMerged(text, dictionaries, alphanumeric, options) { const secondarySearchTitles = Object.keys(options.dictionaries).filter(dict => options.dictionaries[dict].allowSecondarySearches); const titles = Object.keys(dictionaries); -- cgit v1.2.3 From fe829139914bbcb9584f11b6bece798b987fbd8b Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 4 Nov 2019 19:36:50 -0500 Subject: Rename function --- ext/bg/js/translator.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index d04b1cb3..305619a5 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -143,7 +143,7 @@ class Translator { async findTermsGrouped(text, dictionaries, alphanumeric, options) { const titles = Object.keys(dictionaries); - const {length, definitions} = await this.findTerms(text, dictionaries, alphanumeric); + const {length, definitions} = await this.findTermsInternal(text, dictionaries, alphanumeric); const definitionsGrouped = dictTermsGroup(definitions, dictionaries); await this.buildTermFrequencies(definitionsGrouped, titles); @@ -160,7 +160,7 @@ class Translator { async findTermsMerged(text, dictionaries, alphanumeric, options) { const secondarySearchTitles = Object.keys(options.dictionaries).filter(dict => options.dictionaries[dict].allowSecondarySearches); const titles = Object.keys(dictionaries); - const {length, definitions} = await this.findTerms(text, dictionaries, alphanumeric); + const {length, definitions} = await this.findTermsInternal(text, dictionaries, alphanumeric); const {sequencedDefinitions, defaultDefinitions} = await this.getSequencedDefinitions(definitions, options.general.mainDictionary); const definitionsMerged = []; const mergedByTermIndices = new Set(); @@ -196,14 +196,14 @@ class Translator { async findTermsSplit(text, dictionaries, alphanumeric) { const titles = Object.keys(dictionaries); - const {length, definitions} = await this.findTerms(text, dictionaries, alphanumeric); + const {length, definitions} = await this.findTermsInternal(text, dictionaries, alphanumeric); await this.buildTermFrequencies(definitions, titles); return {length, definitions}; } - async findTerms(text, dictionaries, alphanumeric) { + async findTermsInternal(text, dictionaries, alphanumeric) { if (!alphanumeric && text.length > 0) { const c = text[0]; if (!jpIsKana(c) && !jpIsKanji(c)) { -- cgit v1.2.3 From af1662acadbfb7a96e06257a9dfad71ed6e2c478 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 4 Nov 2019 20:09:34 -0500 Subject: Update how apiTermsFind works --- ext/bg/js/api.js | 16 +--------------- ext/bg/js/translator.js | 38 +++++++++++++++++++++++++++----------- 2 files changed, 28 insertions(+), 26 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index 9fed99a1..9751d4a1 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -74,21 +74,7 @@ async function apiOptionsSave(source) { async function apiTermsFind(text, optionsContext) { const options = await apiOptionsGet(optionsContext); - const translator = utilBackend().translator; - - const searcher = { - 'merge': translator.findTermsMerged, - 'split': translator.findTermsSplit, - 'group': translator.findTermsGrouped - }[options.general.resultOutputMode].bind(translator); - - const {definitions, length} = await searcher( - text, - dictEnabledSet(options), - options.scanning.alphanumeric, - options - ); - + const [definitions, length] = await utilBackend().translator.findTerms(text, options); return { length, definitions: definitions.slice(0, options.general.maxResults) diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index 305619a5..d33a2e27 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -141,9 +141,23 @@ class Translator { return result; } - async findTermsGrouped(text, dictionaries, alphanumeric, options) { + async findTerms(text, options) { + switch (options.general.resultOutputMode) { + case 'group': + return await this.findTermsGrouped(text, options); + case 'merge': + return await this.findTermsMerged(text, options); + case 'split': + return await this.findTermsSplit(text, options); + default: + return [[], 0]; + } + } + + async findTermsGrouped(text, options) { + const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); - const {length, definitions} = await this.findTermsInternal(text, dictionaries, alphanumeric); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric); const definitionsGrouped = dictTermsGroup(definitions, dictionaries); await this.buildTermFrequencies(definitionsGrouped, titles); @@ -154,13 +168,14 @@ class Translator { } } - return {length, definitions: definitionsGrouped}; + return [definitionsGrouped, length]; } - async findTermsMerged(text, dictionaries, alphanumeric, options) { + async findTermsMerged(text, options) { + const dictionaries = dictEnabledSet(options); const secondarySearchTitles = Object.keys(options.dictionaries).filter(dict => options.dictionaries[dict].allowSecondarySearches); const titles = Object.keys(dictionaries); - const {length, definitions} = await this.findTermsInternal(text, dictionaries, alphanumeric); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric); const {sequencedDefinitions, defaultDefinitions} = await this.getSequencedDefinitions(definitions, options.general.mainDictionary); const definitionsMerged = []; const mergedByTermIndices = new Set(); @@ -191,23 +206,24 @@ class Translator { } } - return {length, definitions: dictTermsSort(definitionsMerged)}; + return [dictTermsSort(definitionsMerged), length]; } - async findTermsSplit(text, dictionaries, alphanumeric) { + async findTermsSplit(text, options) { + const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); - const {length, definitions} = await this.findTermsInternal(text, dictionaries, alphanumeric); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric); await this.buildTermFrequencies(definitions, titles); - return {length, definitions}; + return [definitions, length]; } async findTermsInternal(text, dictionaries, alphanumeric) { if (!alphanumeric && text.length > 0) { const c = text[0]; if (!jpIsKana(c) && !jpIsKanji(c)) { - return {length: 0, definitions: []}; + return [[], 0]; } } @@ -246,7 +262,7 @@ class Translator { length = Math.max(length, definition.source.length); } - return {length, definitions}; + return [definitions, length]; } async findTermDeinflections(text, text2, titles) { -- cgit v1.2.3 From 58c099799940fce56c7a57ce566c522c7eb0eb12 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 4 Nov 2019 20:13:03 -0500 Subject: Give findKanji the same API as findTerms --- ext/bg/js/api.js | 2 +- ext/bg/js/translator.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index 9751d4a1..f379e65a 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -83,7 +83,7 @@ async function apiTermsFind(text, optionsContext) { async function apiKanjiFind(text, optionsContext) { const options = await apiOptionsGet(optionsContext); - const definitions = await utilBackend().translator.findKanji(text, dictEnabledSet(options)); + const definitions = await utilBackend().translator.findKanji(text, options); return definitions.slice(0, options.general.maxResults); } diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index d33a2e27..1cdd79db 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -330,7 +330,8 @@ class Translator { return deinflections; } - async findKanji(text, dictionaries) { + async findKanji(text, options) { + const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); const kanjiUnique = {}; const kanjiList = []; -- cgit v1.2.3 From 3a225c3f916d435e04fb30afa731c30c4309fc7f Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 4 Nov 2019 20:43:40 -0500 Subject: Add details field to apiTermsFind --- ext/bg/js/api.js | 4 ++-- ext/bg/js/backend.js | 2 +- ext/bg/js/search.js | 2 +- ext/bg/js/translator.js | 22 +++++++++++----------- ext/fg/js/api.js | 4 ++-- ext/fg/js/frontend.js | 2 +- ext/mixed/js/display.js | 2 +- 7 files changed, 19 insertions(+), 19 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index c50db76f..df73aa2a 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -72,9 +72,9 @@ async function apiOptionsSave(source) { backend.onOptionsUpdated(source); } -async function apiTermsFind(text, optionsContext) { +async function apiTermsFind(text, details, optionsContext) { const options = await apiOptionsGet(optionsContext); - const [definitions, length] = await utilBackend().translator.findTerms(text, options); + const [definitions, length] = await utilBackend().translator.findTerms(text, details, options); definitions.splice(options.general.maxResults); return {length, definitions}; } diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 71393467..efad153a 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -179,7 +179,7 @@ Backend.messageHandlers = { optionsGet: ({optionsContext}) => apiOptionsGet(optionsContext), optionsSet: ({changedOptions, optionsContext, source}) => apiOptionsSet(changedOptions, optionsContext, source), kanjiFind: ({text, optionsContext}) => apiKanjiFind(text, optionsContext), - termsFind: ({text, optionsContext}) => apiTermsFind(text, optionsContext), + termsFind: ({text, details, optionsContext}) => apiTermsFind(text, details, optionsContext), definitionAdd: ({definition, mode, context, optionsContext}) => apiDefinitionAdd(definition, mode, context, optionsContext), definitionsAddable: ({definitions, modes, optionsContext}) => apiDefinitionsAddable(definitions, modes, optionsContext), noteView: ({noteId}) => apiNoteView(noteId), diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index ad579918..abd40640 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -207,7 +207,7 @@ class DisplaySearch extends Display { this.setIntroVisible(!valid, animate); this.updateSearchButton(); if (valid) { - const {definitions} = await apiTermsFind(query, this.optionsContext); + const {definitions} = await apiTermsFind(query, {}, this.optionsContext); this.setContentTerms(definitions, { focus: false, sentence: null, diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index 1cdd79db..dac53f93 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -141,23 +141,23 @@ class Translator { return result; } - async findTerms(text, options) { + async findTerms(text, details, options) { switch (options.general.resultOutputMode) { case 'group': - return await this.findTermsGrouped(text, options); + return await this.findTermsGrouped(text, details, options); case 'merge': - return await this.findTermsMerged(text, options); + return await this.findTermsMerged(text, details, options); case 'split': - return await this.findTermsSplit(text, options); + return await this.findTermsSplit(text, details, options); default: return [[], 0]; } } - async findTermsGrouped(text, options) { + async findTermsGrouped(text, details, options) { const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); - const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details); const definitionsGrouped = dictTermsGroup(definitions, dictionaries); await this.buildTermFrequencies(definitionsGrouped, titles); @@ -171,11 +171,11 @@ class Translator { return [definitionsGrouped, length]; } - async findTermsMerged(text, options) { + async findTermsMerged(text, details, options) { const dictionaries = dictEnabledSet(options); const secondarySearchTitles = Object.keys(options.dictionaries).filter(dict => options.dictionaries[dict].allowSecondarySearches); const titles = Object.keys(dictionaries); - const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details); const {sequencedDefinitions, defaultDefinitions} = await this.getSequencedDefinitions(definitions, options.general.mainDictionary); const definitionsMerged = []; const mergedByTermIndices = new Set(); @@ -209,17 +209,17 @@ class Translator { return [dictTermsSort(definitionsMerged), length]; } - async findTermsSplit(text, options) { + async findTermsSplit(text, details, options) { const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); - const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details); await this.buildTermFrequencies(definitions, titles); return [definitions, length]; } - async findTermsInternal(text, dictionaries, alphanumeric) { + async findTermsInternal(text, dictionaries, alphanumeric, details) { if (!alphanumeric && text.length > 0) { const c = text[0]; if (!jpIsKana(c) && !jpIsKanji(c)) { diff --git a/ext/fg/js/api.js b/ext/fg/js/api.js index 54818702..945ba076 100644 --- a/ext/fg/js/api.js +++ b/ext/fg/js/api.js @@ -25,8 +25,8 @@ function apiOptionsSet(changedOptions, optionsContext, source) { return utilInvoke('optionsSet', {changedOptions, optionsContext, source}); } -function apiTermsFind(text, optionsContext) { - return utilInvoke('termsFind', {text, optionsContext}); +function apiTermsFind(text, details, optionsContext) { + return utilInvoke('termsFind', {text, details, optionsContext}); } function apiKanjiFind(text, optionsContext) { diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index 7c62b51b..6002dfcb 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -413,7 +413,7 @@ class Frontend { const searchText = textSource.text(); if (searchText.length === 0) { return null; } - const {definitions, length} = await apiTermsFind(searchText, this.getOptionsContext()); + const {definitions, length} = await apiTermsFind(searchText, {}, this.getOptionsContext()); if (definitions.length === 0) { return null; } textSource.setEndOffset(length); diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index 801011df..8ad3ee1b 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -112,7 +112,7 @@ class Display { try { textSource.setEndOffset(this.options.scanning.length); - ({definitions, length} = await apiTermsFind(textSource.text(), this.getOptionsContext())); + ({definitions, length} = await apiTermsFind(textSource.text(), {}, this.getOptionsContext())); if (definitions.length === 0) { return false; } -- cgit v1.2.3 From 7333873244ccaeeefe01bd3a63447f39dd4f3bbe Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 4 Nov 2019 20:52:08 -0500 Subject: Add support for wildcards --- ext/bg/js/database.js | 9 +++++---- ext/bg/js/search.js | 9 ++++++++- ext/bg/js/translator.js | 27 +++++++++++++++++++++++---- 3 files changed, 36 insertions(+), 9 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index b6cf9063..9b560f78 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -130,7 +130,7 @@ class Database { await Promise.all(promises); } - async findTermsBulk(termList, titles) { + async findTermsBulk(termList, titles, wildcard) { this.validate(); const promises = []; @@ -149,10 +149,11 @@ class Database { const dbIndex2 = dbTerms.index('reading'); for (let i = 0; i < termList.length; ++i) { - const only = IDBKeyRange.only(termList[i]); + const term = termList[i]; + const query = wildcard ? IDBKeyRange.bound(term, `${term}\uffff`, false, false) : IDBKeyRange.only(term); promises.push( - Database.getAll(dbIndex1, only, i, processRow), - Database.getAll(dbIndex2, only, i, processRow) + Database.getAll(dbIndex1, query, i, processRow), + Database.getAll(dbIndex2, query, i, processRow) ); } diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index abd40640..aa56d1a6 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -203,11 +203,18 @@ class DisplaySearch extends Display { async onSearchQueryUpdated(query, animate) { try { + const details = {}; + const match = /[\*\uff0a]+$/.exec(query); + if (match !== null) { + details.wildcard = true; + query = query.substr(0, query.length - match[0].length); + } + const valid = (query.length > 0); this.setIntroVisible(!valid, animate); this.updateSearchButton(); if (valid) { - const {definitions} = await apiTermsFind(query, {}, this.optionsContext); + const {definitions} = await apiTermsFind(query, details, this.optionsContext); this.setContentTerms(definitions, { focus: false, sentence: null, diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index dac53f93..583d6e31 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -227,9 +227,12 @@ class Translator { } } - const textHiragana = jpKatakanaToHiragana(text); const titles = Object.keys(dictionaries); - const deinflections = await this.findTermDeinflections(text, textHiragana, titles); + const deinflections = ( + details.wildcard ? + await this.findTermWildcard(text, titles) : + await this.findTermDeinflections(text, titles) + ); let definitions = []; for (const deinflection of deinflections) { @@ -265,7 +268,23 @@ class Translator { return [definitions, length]; } - async findTermDeinflections(text, text2, titles) { + async findTermWildcard(text, titles) { + const definitions = await this.database.findTermsBulk([text], titles, true); + if (definitions.length === 0) { + return []; + } + + return [{ + source: text, + term: text, + rules: 0, + definitions, + reasons: [] + }]; + } + + async findTermDeinflections(text, titles) { + const text2 = jpKatakanaToHiragana(text); const deinflections = (text === text2 ? this.getDeinflections(text) : this.getDeinflections2(text, text2)); if (deinflections.length === 0) { @@ -289,7 +308,7 @@ class Translator { deinflectionArray.push(deinflection); } - const definitions = await this.database.findTermsBulk(uniqueDeinflectionTerms, titles); + const definitions = await this.database.findTermsBulk(uniqueDeinflectionTerms, titles, false); for (const definition of definitions) { const definitionRules = Deinflector.rulesToRuleFlags(definition.rules); -- cgit v1.2.3 From cf18e3b42e0fa171b9ec9af4c534a962d347e155 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sun, 24 Nov 2019 11:02:52 -0500 Subject: Replace string.substr and string.slice with string.substring Improves semantic clarity, and it's recommended to not use substr. --- ext/bg/js/audio.js | 2 +- ext/bg/js/deinflector.js | 2 +- ext/bg/js/search.js | 2 +- ext/bg/js/translator.js | 20 ++++++++++---------- ext/fg/js/popup.js | 2 +- ext/mixed/js/audio.js | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/audio.js b/ext/bg/js/audio.js index 3efcce46..cd42a158 100644 --- a/ext/bg/js/audio.js +++ b/ext/bg/js/audio.js @@ -128,7 +128,7 @@ function audioUrlNormalize(url, baseUrl, basePath) { if (url[0] === '/') { if (url.length >= 2 && url[1] === '/') { // Begins with "//" - url = baseUrl.substr(0, baseUrl.indexOf(':') + 1) + url; + url = baseUrl.substring(0, baseUrl.indexOf(':') + 1) + url; } else { // Begins with "/" url = baseUrl + url; diff --git a/ext/bg/js/deinflector.js b/ext/bg/js/deinflector.js index ce4b2961..e2fb7461 100644 --- a/ext/bg/js/deinflector.js +++ b/ext/bg/js/deinflector.js @@ -44,7 +44,7 @@ class Deinflector { results.push({ source, - term: term.slice(0, -kanaIn.length) + kanaOut, + term: term.substring(0, term.length - kanaIn.length) + kanaOut, rules: rulesOut, definitions: [], reasons: [reason, ...reasons] diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index 56316217..ec5a5972 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -207,7 +207,7 @@ class DisplaySearch extends Display { const match = /[\*\uff0a]+$/.exec(query); if (match !== null) { details.wildcard = true; - query = query.substr(0, query.length - match[0].length); + query = query.substring(0, query.length - match[0].length); } const valid = (query.length > 0); diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index 583d6e31..e27cbdff 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -327,22 +327,22 @@ class Translator { const deinflections = []; for (let i = text.length; i > 0; --i) { - const textSlice = text.slice(0, i); - deinflections.push(...this.deinflector.deinflect(textSlice)); + const textSubstring = text.substring(0, i); + deinflections.push(...this.deinflector.deinflect(textSubstring)); } return deinflections; } - getDeinflections2(text, text2) { + getDeinflections2(text1, text2) { const deinflections = []; - for (let i = text.length; i > 0; --i) { - const textSlice = text.slice(0, i); - const text2Slice = text2.slice(0, i); - deinflections.push(...this.deinflector.deinflect(textSlice)); - if (textSlice !== text2Slice) { - deinflections.push(...this.deinflector.deinflect(text2Slice)); + for (let i = text1.length; i > 0; --i) { + const text1Substring = text1.substring(0, i); + const text2Substring = text2.substring(0, i); + deinflections.push(...this.deinflector.deinflect(text1Substring)); + if (text1Substring !== text2Substring) { + deinflections.push(...this.deinflector.deinflect(text2Substring)); } } @@ -516,6 +516,6 @@ class Translator { static getNameBase(name) { const pos = name.indexOf(':'); - return (pos >= 0 ? name.substr(0, pos) : name); + return (pos >= 0 ? name.substring(0, pos) : name); } } diff --git a/ext/fg/js/popup.js b/ext/fg/js/popup.js index 1f9317e0..ac96f9e8 100644 --- a/ext/fg/js/popup.js +++ b/ext/fg/js/popup.js @@ -391,7 +391,7 @@ class Popup { static isOnExtensionPage() { try { const url = chrome.runtime.getURL('/'); - return window.location.href.substr(0, url.length) === url; + return window.location.href.substring(0, url.length) === url; } catch (e) { // NOP } diff --git a/ext/mixed/js/audio.js b/ext/mixed/js/audio.js index ff50dee1..4e9d04fa 100644 --- a/ext/mixed/js/audio.js +++ b/ext/mixed/js/audio.js @@ -75,7 +75,7 @@ class TextToSpeechAudio { for (const group of m[1].split('&')) { const sep = group.indexOf('='); if (sep < 0) { continue; } - searchParameters[decodeURIComponent(group.substr(0, sep))] = decodeURIComponent(group.substr(sep + 1)); + searchParameters[decodeURIComponent(group.substring(0, sep))] = decodeURIComponent(group.substring(sep + 1)); } if (!searchParameters.text) { return null; } -- cgit v1.2.3 From 0aed27b66d9c496e4cd57ef95d982c4e634a8666 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 25 Nov 2019 14:19:18 -0500 Subject: Replace hasOwnProperty with simplified hasOwn function --- ext/bg/js/api.js | 4 ++-- ext/bg/js/audio.js | 6 +++--- ext/bg/js/backend.js | 2 +- ext/bg/js/conditions-ui.js | 20 ++++++++++---------- ext/bg/js/conditions.js | 30 +++++++++++++++--------------- ext/bg/js/database.js | 2 +- ext/bg/js/dictionary.js | 4 ++-- ext/bg/js/mecab.js | 2 +- ext/bg/js/options.js | 2 +- ext/bg/js/search.js | 2 +- ext/bg/js/settings-dictionaries.js | 4 ++-- ext/bg/js/settings-popup-preview.js | 2 +- ext/bg/js/translator.js | 12 ++++++------ ext/fg/js/float.js | 4 ++-- ext/fg/js/frontend-api-receiver.js | 2 +- ext/fg/js/frontend-api-sender.js | 6 +++--- ext/fg/js/frontend.js | 4 ++-- ext/fg/js/popup-proxy-host.js | 4 ++-- ext/mixed/js/audio.js | 2 +- ext/mixed/js/core.js | 4 ++++ ext/mixed/js/display.js | 4 ++-- 21 files changed, 63 insertions(+), 59 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index 766fb0ed..12257e92 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -45,7 +45,7 @@ async function apiOptionsSet(changedOptions, optionsContext, source) { function modifyOption(path, value, options) { let pivot = options; for (const key of path.slice(0, -1)) { - if (!pivot.hasOwnProperty(key)) { + if (!hasOwn(pivot, key)) { return false; } pivot = pivot[key]; @@ -236,7 +236,7 @@ async function apiTemplateRender(template, data, dynamic) { async function apiCommandExec(command, params) { const handlers = apiCommandExec.handlers; - if (handlers.hasOwnProperty(command)) { + if (hasOwn(handlers, command)) { const handler = handlers[command]; handler(params); } diff --git a/ext/bg/js/audio.js b/ext/bg/js/audio.js index cd42a158..9bbbf902 100644 --- a/ext/bg/js/audio.js +++ b/ext/bg/js/audio.js @@ -107,12 +107,12 @@ const audioUrlBuilders = { 'custom': async (definition, optionsContext) => { const options = await apiOptionsGet(optionsContext); const customSourceUrl = options.audio.customSourceUrl; - return customSourceUrl.replace(/\{([^\}]*)\}/g, (m0, m1) => (definition.hasOwnProperty(m1) ? `${definition[m1]}` : m0)); + return customSourceUrl.replace(/\{([^\}]*)\}/g, (m0, m1) => (hasOwn(definition, m1) ? `${definition[m1]}` : m0)); } }; async function audioGetUrl(definition, mode, optionsContext, download) { - if (audioUrlBuilders.hasOwnProperty(mode)) { + if (hasOwn(audioUrlBuilders, mode)) { const handler = audioUrlBuilders[mode]; try { return await handler(definition, optionsContext, download); @@ -171,7 +171,7 @@ async function audioInject(definition, fields, sources, optionsContext) { try { let audioSourceDefinition = definition; - if (definition.hasOwnProperty('expressions')) { + if (hasOwn(definition, 'expressions')) { audioSourceDefinition = definition.expressions[0]; } diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 45db9660..4190116b 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -73,7 +73,7 @@ class Backend { onMessage({action, params}, sender, callback) { const handlers = Backend.messageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const promise = handler(params, sender); promise.then( diff --git a/ext/bg/js/conditions-ui.js b/ext/bg/js/conditions-ui.js index 43c6dc08..cc9db087 100644 --- a/ext/bg/js/conditions-ui.js +++ b/ext/bg/js/conditions-ui.js @@ -84,7 +84,7 @@ ConditionsUI.Container = class Container { createDefaultCondition(type) { let operator = ''; let value = ''; - if (this.conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(this.conditionDescriptors, type)) { const conditionDescriptor = this.conditionDescriptors[type]; operator = conditionDescriptor.defaultOperator; ({value} = this.getOperatorDefaultValue(type, operator)); @@ -96,15 +96,15 @@ ConditionsUI.Container = class Container { } getOperatorDefaultValue(type, operator) { - if (this.conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(this.conditionDescriptors, type)) { const conditionDescriptor = this.conditionDescriptors[type]; - if (conditionDescriptor.operators.hasOwnProperty(operator)) { + if (hasOwn(conditionDescriptor.operators, operator)) { const operatorDescriptor = conditionDescriptor.operators[operator]; - if (operatorDescriptor.hasOwnProperty('defaultValue')) { + if (hasOwn(operatorDescriptor, 'defaultValue')) { return {value: operatorDescriptor.defaultValue, fromOperator: true}; } } - if (conditionDescriptor.hasOwnProperty('defaultValue')) { + if (hasOwn(conditionDescriptor, 'defaultValue')) { return {value: conditionDescriptor.defaultValue, fromOperator: false}; } } @@ -219,7 +219,7 @@ ConditionsUI.Condition = class Condition { optionGroup.empty(); const type = this.condition.type; - if (conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(conditionDescriptors, type)) { const conditionDescriptor = conditionDescriptors[type]; const operators = conditionDescriptor.operators; for (const operatorName of Object.keys(operators)) { @@ -240,23 +240,23 @@ ConditionsUI.Condition = class Condition { }; const objects = []; - if (conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(conditionDescriptors, type)) { const conditionDescriptor = conditionDescriptors[type]; objects.push(conditionDescriptor); - if (conditionDescriptor.operators.hasOwnProperty(operator)) { + if (hasOwn(conditionDescriptor.operators, operator)) { const operatorDescriptor = conditionDescriptor.operators[operator]; objects.push(operatorDescriptor); } } for (const object of objects) { - if (object.hasOwnProperty('placeholder')) { + if (hasOwn(object, 'placeholder')) { props.placeholder = object.placeholder; } if (object.type === 'number') { props.type = 'number'; for (const prop of ['step', 'min', 'max']) { - if (object.hasOwnProperty(prop)) { + if (hasOwn(object, prop)) { props[prop] = object[prop]; } } diff --git a/ext/bg/js/conditions.js b/ext/bg/js/conditions.js index ed4b14f5..c0f0f301 100644 --- a/ext/bg/js/conditions.js +++ b/ext/bg/js/conditions.js @@ -18,14 +18,14 @@ function conditionsValidateOptionValue(object, value) { - if (object.hasOwnProperty('validate') && !object.validate(value)) { + if (hasOwn(object, 'validate') && !object.validate(value)) { throw new Error('Invalid value for condition'); } - if (object.hasOwnProperty('transform')) { + if (hasOwn(object, 'transform')) { value = object.transform(value); - if (object.hasOwnProperty('validateTransformed') && !object.validateTransformed(value)) { + if (hasOwn(object, 'validateTransformed') && !object.validateTransformed(value)) { throw new Error('Invalid value for condition'); } } @@ -34,12 +34,12 @@ function conditionsValidateOptionValue(object, value) { } function conditionsNormalizeOptionValue(descriptors, type, operator, optionValue) { - if (!descriptors.hasOwnProperty(type)) { + if (!hasOwn(descriptors, type)) { throw new Error('Invalid type'); } const conditionDescriptor = descriptors[type]; - if (!conditionDescriptor.operators.hasOwnProperty(operator)) { + if (!hasOwn(conditionDescriptor.operators, operator)) { throw new Error('Invalid operator'); } @@ -48,28 +48,28 @@ function conditionsNormalizeOptionValue(descriptors, type, operator, optionValue let transformedValue = conditionsValidateOptionValue(conditionDescriptor, optionValue); transformedValue = conditionsValidateOptionValue(operatorDescriptor, transformedValue); - if (operatorDescriptor.hasOwnProperty('transformReverse')) { + if (hasOwn(operatorDescriptor, 'transformReverse')) { transformedValue = operatorDescriptor.transformReverse(transformedValue); } return transformedValue; } function conditionsTestValueThrowing(descriptors, type, operator, optionValue, value) { - if (!descriptors.hasOwnProperty(type)) { + if (!hasOwn(descriptors, type)) { throw new Error('Invalid type'); } const conditionDescriptor = descriptors[type]; - if (!conditionDescriptor.operators.hasOwnProperty(operator)) { + if (!hasOwn(conditionDescriptor.operators, operator)) { throw new Error('Invalid operator'); } const operatorDescriptor = conditionDescriptor.operators[operator]; - if (operatorDescriptor.hasOwnProperty('transform')) { - if (operatorDescriptor.hasOwnProperty('transformCache')) { + if (hasOwn(operatorDescriptor, 'transform')) { + if (hasOwn(operatorDescriptor, 'transformCache')) { const key = `${optionValue}`; const transformCache = operatorDescriptor.transformCache; - if (transformCache.hasOwnProperty(key)) { + if (hasOwn(transformCache, key)) { optionValue = transformCache[key]; } else { optionValue = operatorDescriptor.transform(optionValue); @@ -93,23 +93,23 @@ function conditionsTestValue(descriptors, type, operator, optionValue, value) { function conditionsClearCaches(descriptors) { for (const type in descriptors) { - if (!descriptors.hasOwnProperty(type)) { + if (!hasOwn(descriptors, type)) { continue; } const conditionDescriptor = descriptors[type]; - if (conditionDescriptor.hasOwnProperty('transformCache')) { + if (hasOwn(conditionDescriptor, 'transformCache')) { conditionDescriptor.transformCache = {}; } const operatorDescriptors = conditionDescriptor.operators; for (const operator in operatorDescriptors) { - if (!operatorDescriptors.hasOwnProperty(operator)) { + if (!hasOwn(operatorDescriptors, operator)) { continue; } const operatorDescriptor = operatorDescriptors[operator]; - if (operatorDescriptor.hasOwnProperty('transformCache')) { + if (hasOwn(operatorDescriptor, 'transformCache')) { operatorDescriptor.transformCache = {}; } } diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index 9b560f78..c53c9f77 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -137,7 +137,7 @@ class Database { const visited = {}; const results = []; const processRow = (row, index) => { - if (titles.includes(row.dictionary) && !visited.hasOwnProperty(row.id)) { + if (titles.includes(row.dictionary) && !hasOwn(visited, row.id)) { visited[row.id] = true; results.push(Database.createTerm(row, index)); } diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js index 9aa0af9c..affce9e9 100644 --- a/ext/bg/js/dictionary.js +++ b/ext/bg/js/dictionary.js @@ -81,7 +81,7 @@ function dictTermsUndupe(definitions) { const definitionGroups = {}; for (const definition of definitions) { const definitionExisting = definitionGroups[definition.id]; - if (!definitionGroups.hasOwnProperty(definition.id) || definition.expression.length > definitionExisting.expression.length) { + if (!hasOwn(definitionGroups, definition.id) || definition.expression.length > definitionExisting.expression.length) { definitionGroups[definition.id] = definition; } } @@ -131,7 +131,7 @@ function dictTermsGroup(definitions, dictionaries) { } const keyString = key.toString(); - if (groups.hasOwnProperty(keyString)) { + if (hasOwn(groups, keyString)) { groups[keyString].push(definition); } else { groups[keyString] = [definition]; diff --git a/ext/bg/js/mecab.js b/ext/bg/js/mecab.js index 246f8bba..297432e2 100644 --- a/ext/bg/js/mecab.js +++ b/ext/bg/js/mecab.js @@ -60,7 +60,7 @@ class Mecab { } onNativeMessage({sequence, data}) { - if (this.listeners.hasOwnProperty(sequence)) { + if (hasOwn(this.listeners, sequence)) { const {callback, timer} = this.listeners[sequence]; clearTimeout(timer); callback(data); diff --git a/ext/bg/js/options.js b/ext/bg/js/options.js index 63d88789..358a6b45 100644 --- a/ext/bg/js/options.js +++ b/ext/bg/js/options.js @@ -336,7 +336,7 @@ function profileOptionsSetDefaults(options) { const combine = (target, source) => { for (const key in source) { - if (!target.hasOwnProperty(key)) { + if (!hasOwn(target, key)) { target[key] = source[key]; } } diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index 0922d938..16cbfbbd 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -234,7 +234,7 @@ class DisplaySearch extends Display { onRuntimeMessage({action, params}, sender, callback) { const handlers = DisplaySearch.runtimeMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const result = handler(this, params); callback(result); diff --git a/ext/bg/js/settings-dictionaries.js b/ext/bg/js/settings-dictionaries.js index ebd380ac..177379b0 100644 --- a/ext/bg/js/settings-dictionaries.js +++ b/ext/bg/js/settings-dictionaries.js @@ -81,7 +81,7 @@ class SettingsDictionaryListUI { let changed = false; let optionsDictionary; const optionsDictionaries = this.optionsDictionaries; - if (optionsDictionaries.hasOwnProperty(title)) { + if (hasOwn(optionsDictionaries, title)) { optionsDictionary = optionsDictionaries[title]; } else { optionsDictionary = SettingsDictionaryListUI.createDictionaryOptions(); @@ -466,7 +466,7 @@ function dictionaryErrorsShow(errors) { for (let e of errors) { console.error(e); e = dictionaryErrorToString(e); - uniqueErrors[e] = uniqueErrors.hasOwnProperty(e) ? uniqueErrors[e] + 1 : 1; + uniqueErrors[e] = hasOwn(uniqueErrors, e) ? uniqueErrors[e] + 1 : 1; } for (const e in uniqueErrors) { diff --git a/ext/bg/js/settings-popup-preview.js b/ext/bg/js/settings-popup-preview.js index 7d641c46..49409968 100644 --- a/ext/bg/js/settings-popup-preview.js +++ b/ext/bg/js/settings-popup-preview.js @@ -106,7 +106,7 @@ class SettingsPopupPreview { onMessage(e) { const {action, params} = e.data; const handlers = SettingsPopupPreview.messageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; handler(this, params); } diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index e27cbdff..0a0ce663 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -297,7 +297,7 @@ class Translator { for (const deinflection of deinflections) { const term = deinflection.term; let deinflectionArray; - if (uniqueDeinflectionsMap.hasOwnProperty(term)) { + if (hasOwn(uniqueDeinflectionsMap, term)) { deinflectionArray = uniqueDeinflectionsMap[term]; } else { deinflectionArray = []; @@ -355,7 +355,7 @@ class Translator { const kanjiUnique = {}; const kanjiList = []; for (const c of text) { - if (!kanjiUnique.hasOwnProperty(c)) { + if (!hasOwn(kanjiUnique, c)) { kanjiList.push(c); kanjiUnique[c] = true; } @@ -417,7 +417,7 @@ class Translator { const expression = term.expression; term.frequencies = []; - if (termsUniqueMap.hasOwnProperty(expression)) { + if (hasOwn(termsUniqueMap, expression)) { termsUniqueMap[expression].push(term); } else { const termList = [term]; @@ -464,7 +464,7 @@ class Translator { const category = meta.category; const group = ( - stats.hasOwnProperty(category) ? + hasOwn(stats, category) ? stats[category] : (stats[category] = []) ); @@ -484,7 +484,7 @@ class Translator { async getTagMetaList(names, title) { const tagMetaList = []; const cache = ( - this.tagCache.hasOwnProperty(title) ? + hasOwn(this.tagCache, title) ? this.tagCache[title] : (this.tagCache[title] = {}) ); @@ -492,7 +492,7 @@ class Translator { for (const name of names) { const base = Translator.getNameBase(name); - if (cache.hasOwnProperty(base)) { + if (hasOwn(cache, base)) { tagMetaList.push(cache[base]); } else { const tagMeta = await this.database.findTagForTitle(base, title); diff --git a/ext/fg/js/float.js b/ext/fg/js/float.js index 089c9422..ae54be00 100644 --- a/ext/fg/js/float.js +++ b/ext/fg/js/float.js @@ -49,7 +49,7 @@ class DisplayFloat extends Display { onMessage(e) { const {action, params} = e.data; const handlers = DisplayFloat.messageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; handler(this, params); } @@ -58,7 +58,7 @@ class DisplayFloat extends Display { onKeyDown(e) { const key = Display.getKeyFromEvent(e); const handlers = DisplayFloat.onKeyDownHandlers; - if (handlers.hasOwnProperty(key)) { + if (hasOwn(handlers, key)) { const handler = handlers[key]; if (handler(this, e)) { e.preventDefault(); diff --git a/ext/fg/js/frontend-api-receiver.js b/ext/fg/js/frontend-api-receiver.js index fbfb3ab0..bde14646 100644 --- a/ext/fg/js/frontend-api-receiver.js +++ b/ext/fg/js/frontend-api-receiver.js @@ -34,7 +34,7 @@ class FrontendApiReceiver { onMessage(port, {id, action, params, target, senderId}) { if ( target !== this.source || - !this.handlers.hasOwnProperty(action) + !hasOwn(this.handlers, action) ) { return; } diff --git a/ext/fg/js/frontend-api-sender.js b/ext/fg/js/frontend-api-sender.js index c6eeaeb2..af998a8f 100644 --- a/ext/fg/js/frontend-api-sender.js +++ b/ext/fg/js/frontend-api-sender.js @@ -78,7 +78,7 @@ class FrontendApiSender { } onAck(id) { - if (!this.callbacks.hasOwnProperty(id)) { + if (!hasOwn(this.callbacks, id)) { console.warn(`ID ${id} not found for ack`); return; } @@ -95,7 +95,7 @@ class FrontendApiSender { } onResult(id, data) { - if (!this.callbacks.hasOwnProperty(id)) { + if (!hasOwn(this.callbacks, id)) { console.warn(`ID ${id} not found`); return; } @@ -118,7 +118,7 @@ class FrontendApiSender { } onError(id, reason) { - if (!this.callbacks.hasOwnProperty(id)) { return; } + if (!hasOwn(this.callbacks, id)) { return; } const info = this.callbacks[id]; delete this.callbacks[id]; info.timer = null; diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index ee653d78..16302e82 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -237,7 +237,7 @@ class Frontend { onWindowMessage(e) { const action = e.data; const handlers = Frontend.windowMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; handler(this); } @@ -245,7 +245,7 @@ class Frontend { onRuntimeMessage({action, params}, sender, callback) { const handlers = Frontend.runtimeMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const result = handler(this, params); callback(result); diff --git a/ext/fg/js/popup-proxy-host.js b/ext/fg/js/popup-proxy-host.js index d8dec4df..b2f18b97 100644 --- a/ext/fg/js/popup-proxy-host.js +++ b/ext/fg/js/popup-proxy-host.js @@ -50,7 +50,7 @@ class PopupProxyHost { } createPopup(parentId, depth) { - const parent = (typeof parentId === 'string' && this.popups.hasOwnProperty(parentId) ? this.popups[parentId] : null); + const parent = (typeof parentId === 'string' && hasOwn(this.popups, parentId) ? this.popups[parentId] : null); const id = `${this.nextId}`; if (parent !== null) { depth = parent.depth + 1; @@ -70,7 +70,7 @@ class PopupProxyHost { } getPopup(id) { - if (!this.popups.hasOwnProperty(id)) { + if (!hasOwn(this.popups, id)) { throw new Error('Invalid popup ID'); } diff --git a/ext/mixed/js/audio.js b/ext/mixed/js/audio.js index 4e9d04fa..7d5ffedd 100644 --- a/ext/mixed/js/audio.js +++ b/ext/mixed/js/audio.js @@ -113,7 +113,7 @@ function audioGetFromUrl(url, willDownload) { async function audioGetFromSources(expression, sources, optionsContext, willDownload, cache=null) { const key = `${expression.expression}:${expression.reading}`; - if (cache !== null && cache.hasOwnProperty(expression)) { + if (cache !== null && hasOwn(cache, expression)) { return cache[key]; } diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js index 8a8a2368..d82b9b4b 100644 --- a/ext/mixed/js/core.js +++ b/ext/mixed/js/core.js @@ -94,6 +94,10 @@ function isObject(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); } +function hasOwn(object, property) { + return Object.prototype.hasOwnProperty.call(object, property); +} + // toIterable is required on Edge for cross-window origin objects. function toIterable(value) { if (typeof Symbol !== 'undefined' && typeof value[Symbol.iterator] !== 'undefined') { diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index 854418f4..ce43b22c 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -194,7 +194,7 @@ class Display { onKeyDown(e) { const key = Display.getKeyFromEvent(e); const handlers = Display.onKeyDownHandlers; - if (handlers.hasOwnProperty(key)) { + if (hasOwn(handlers, key)) { const handler = handlers[key]; if (handler(this, e)) { e.preventDefault(); @@ -216,7 +216,7 @@ class Display { onRuntimeMessage({action, params}, sender, callback) { const handlers = Display.runtimeMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const result = handler(this, params); callback(result); -- cgit v1.2.3 From 5a1046bc906a74ca39906a52acc62fc702a658f2 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 26 Nov 2019 22:01:54 -0500 Subject: Update arrow-parens to always --- .eslintrc.json | 2 +- ext/bg/js/anki.js | 2 +- ext/bg/js/api.js | 2 +- ext/bg/js/backend-api-forwarder.js | 4 ++-- ext/bg/js/backend.js | 6 +++--- ext/bg/js/context.js | 2 +- ext/bg/js/database.js | 22 +++++++++++----------- ext/bg/js/dictionary.js | 10 +++++----- ext/bg/js/options.js | 6 +++--- ext/bg/js/profile-conditions.js | 2 +- ext/bg/js/request.js | 2 +- ext/bg/js/search-query-parser.js | 4 ++-- ext/bg/js/settings-dictionaries.js | 10 +++++----- ext/bg/js/settings-profiles.js | 2 +- ext/bg/js/settings.js | 8 ++++---- ext/bg/js/translator.js | 8 ++++---- ext/bg/js/util.js | 4 ++-- ext/fg/js/frontend-api-receiver.js | 4 ++-- ext/fg/js/popup.js | 4 ++-- ext/mixed/js/core.js | 2 +- 20 files changed, 53 insertions(+), 53 deletions(-) (limited to 'ext/bg/js/translator.js') diff --git a/.eslintrc.json b/.eslintrc.json index fce4b884..0e3b939a 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -8,7 +8,7 @@ "/ext/bg/js/templates.js" ], "rules": { - "arrow-parens": ["error", "as-needed"], + "arrow-parens": ["error", "always"], "comma-dangle": ["error", "never"], "curly": ["error", "all"], "dot-notation": "error", diff --git a/ext/bg/js/anki.js b/ext/bg/js/anki.js index ac45784b..17b93620 100644 --- a/ext/bg/js/anki.js +++ b/ext/bg/js/anki.js @@ -74,7 +74,7 @@ class AnkiConnect { async findNoteIds(notes) { await this.checkVersion(); - const actions = notes.map(note => ({ + const actions = notes.map((note) => ({ action: 'findNotes', params: { query: `deck:"${AnkiConnect.escapeQuery(note.deckName)}" ${AnkiConnect.fieldsToQuery(note.fields)}` diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index d5256acb..b489b8d2 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -207,7 +207,7 @@ async function apiDefinitionsAddable(definitions, modes, optionsContext) { } if (cannotAdd.length > 0) { - const noteIdsArray = await anki.findNoteIds(cannotAdd.map(e => e[0])); + const noteIdsArray = await anki.findNoteIds(cannotAdd.map((e) => e[0])); for (let i = 0, ii = Math.min(cannotAdd.length, noteIdsArray.length); i < ii; ++i) { const noteIds = noteIdsArray[i]; if (noteIds.length > 0) { diff --git a/ext/bg/js/backend-api-forwarder.js b/ext/bg/js/backend-api-forwarder.js index 979afd16..db4d30b9 100644 --- a/ext/bg/js/backend-api-forwarder.js +++ b/ext/bg/js/backend-api-forwarder.js @@ -37,8 +37,8 @@ class BackendApiForwarder { const forwardPort = chrome.tabs.connect(tabId, {name: 'frontend-api-receiver'}); - port.onMessage.addListener(message => forwardPort.postMessage(message)); - forwardPort.onMessage.addListener(message => port.postMessage(message)); + port.onMessage.addListener((message) => forwardPort.postMessage(message)); + forwardPort.onMessage.addListener((message) => port.postMessage(message)); port.onDisconnect.addListener(() => forwardPort.disconnect()); forwardPort.onDisconnect.addListener(() => port.disconnect()); } diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 73df7cf5..d9f9b586 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -60,7 +60,7 @@ class Backend { this.applyOptions(); const callback = () => this.checkLastError(chrome.runtime.lastError); - chrome.tabs.query({}, tabs => { + chrome.tabs.query({}, (tabs) => { for (const tab of tabs) { chrome.tabs.sendMessage(tab.id, {action: 'optionsUpdate', params: {source}}, callback); } @@ -77,8 +77,8 @@ class Backend { const handler = handlers[action]; const promise = handler(params, sender); promise.then( - result => callback({result}), - error => callback({error: errorToJson(error)}) + (result) => callback({result}), + (error) => callback({error: errorToJson(error)}) ); } diff --git a/ext/bg/js/context.js b/ext/bg/js/context.js index b288a79a..38a82636 100644 --- a/ext/bg/js/context.js +++ b/ext/bg/js/context.js @@ -63,7 +63,7 @@ window.addEventListener('DOMContentLoaded', () => { depth: 0, url: window.location.href }; - apiOptionsGet(optionsContext).then(options => { + apiOptionsGet(optionsContext).then((options) => { const toggle = document.querySelector('#enable-search'); toggle.checked = options.general.enable; toggle.addEventListener('change', () => apiCommandExec('toggle'), false); diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index c53c9f77..a20d5f15 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -257,7 +257,7 @@ class Database { const dbTerms = dbTransaction.objectStore('tagMeta'); const dbIndex = dbTerms.index('name'); const only = IDBKeyRange.only(name); - await Database.getAll(dbIndex, only, null, row => { + await Database.getAll(dbIndex, only, null, (row) => { if (title === row.dictionary) { result = row; } @@ -273,7 +273,7 @@ class Database { const dbTransaction = this.db.transaction(['dictionaries'], 'readonly'); const dbDictionaries = dbTransaction.objectStore('dictionaries'); - await Database.getAll(dbDictionaries, null, null, info => results.push(info)); + await Database.getAll(dbDictionaries, null, null, (info) => results.push(info)); return results; } @@ -308,7 +308,7 @@ class Database { counts.push(null); const index = i; const query2 = IDBKeyRange.only(dictionaryNames[i]); - const countPromise = Database.getCounts(targets, query2).then(v => counts[index] = v); + const countPromise = Database.getCounts(targets, query2).then((v) => counts[index] = v); countPromises.push(countPromise); } await Promise.all(countPromises); @@ -346,7 +346,7 @@ class Database { } }; - const indexDataLoaded = async summary => { + const indexDataLoaded = async (summary) => { if (summary.version > 3) { throw new Error('Unsupported dictionary version'); } @@ -522,13 +522,13 @@ class Database { await indexDataLoaded(summary); - const buildTermBankName = index => `term_bank_${index + 1}.json`; - const buildTermMetaBankName = index => `term_meta_bank_${index + 1}.json`; - const buildKanjiBankName = index => `kanji_bank_${index + 1}.json`; - const buildKanjiMetaBankName = index => `kanji_meta_bank_${index + 1}.json`; - const buildTagBankName = index => `tag_bank_${index + 1}.json`; + const buildTermBankName = (index) => `term_bank_${index + 1}.json`; + const buildTermMetaBankName = (index) => `term_meta_bank_${index + 1}.json`; + const buildKanjiBankName = (index) => `kanji_bank_${index + 1}.json`; + const buildKanjiMetaBankName = (index) => `kanji_meta_bank_${index + 1}.json`; + const buildTagBankName = (index) => `tag_bank_${index + 1}.json`; - const countBanks = namer => { + const countBanks = (namer) => { let count = 0; while (zip.files[namer(count)]) { ++count; @@ -657,7 +657,7 @@ class Database { const counts = {}; for (const [objectStoreName, index] of targets) { const n = objectStoreName; - const countPromise = Database.getCount(index, query).then(count => counts[n] = count); + const countPromise = Database.getCount(index, query).then((count) => counts[n] = count); countPromises.push(countPromise); } return Promise.all(countPromises).then(() => counts); diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js index 409bed85..0b35e32e 100644 --- a/ext/bg/js/dictionary.js +++ b/ext/bg/js/dictionary.js @@ -99,8 +99,8 @@ function dictTermsCompressTags(definitions) { let lastPartOfSpeech = ''; for (const definition of definitions) { - const dictionary = JSON.stringify(definition.definitionTags.filter(tag => tag.category === 'dictionary').map(tag => tag.name).sort()); - const partOfSpeech = JSON.stringify(definition.definitionTags.filter(tag => tag.category === 'partOfSpeech').map(tag => tag.name).sort()); + const dictionary = JSON.stringify(definition.definitionTags.filter((tag) => tag.category === 'dictionary').map((tag) => tag.name).sort()); + const partOfSpeech = JSON.stringify(definition.definitionTags.filter((tag) => tag.category === 'partOfSpeech').map((tag) => tag.name).sort()); const filterOutCategories = []; @@ -117,7 +117,7 @@ function dictTermsCompressTags(definitions) { lastPartOfSpeech = partOfSpeech; } - definition.definitionTags = definition.definitionTags.filter(tag => !filterOutCategories.includes(tag.category)); + definition.definitionTags = definition.definitionTags.filter((tag) => !filterOutCategories.includes(tag.category)); } } @@ -231,7 +231,7 @@ function dictTermsMergeByGloss(result, definitions, appendTo, mergedIndices) { result.reading.add(definition.reading); for (const tag of definition.definitionTags) { - if (!definitionsByGloss[gloss].definitionTags.find(existingTag => existingTag.name === tag.name)) { + if (!definitionsByGloss[gloss].definitionTags.find((existingTag) => existingTag.name === tag.name)) { definitionsByGloss[gloss].definitionTags.push(tag); } } @@ -246,7 +246,7 @@ function dictTermsMergeByGloss(result, definitions, appendTo, mergedIndices) { } for (const tag of definition.termTags) { - if (!result.expressions.get(definition.expression).get(definition.reading).find(existingTag => existingTag.name === tag.name)) { + if (!result.expressions.get(definition.expression).get(definition.reading).find((existingTag) => existingTag.name === tag.name)) { result.expressions.get(definition.expression).get(definition.reading).push(tag); } } diff --git a/ext/bg/js/options.js b/ext/bg/js/options.js index 358a6b45..e53a8a13 100644 --- a/ext/bg/js/options.js +++ b/ext/bg/js/options.js @@ -429,7 +429,7 @@ function optionsUpdateVersion(options, defaultProfileOptions) { function optionsLoad() { return new Promise((resolve, reject) => { - chrome.storage.local.get(['options'], store => { + chrome.storage.local.get(['options'], (store) => { const error = chrome.runtime.lastError; if (error) { reject(new Error(error)); @@ -437,7 +437,7 @@ function optionsLoad() { resolve(store.options); } }); - }).then(optionsStr => { + }).then((optionsStr) => { if (typeof optionsStr === 'string') { const options = JSON.parse(optionsStr); if (isObject(options)) { @@ -447,7 +447,7 @@ function optionsLoad() { return {}; }).catch(() => { return {}; - }).then(options => { + }).then((options) => { return ( Array.isArray(options.profiles) ? optionsUpdateVersion(options, {}) : diff --git a/ext/bg/js/profile-conditions.js b/ext/bg/js/profile-conditions.js index 8272e5dd..ebc6680a 100644 --- a/ext/bg/js/profile-conditions.js +++ b/ext/bg/js/profile-conditions.js @@ -86,7 +86,7 @@ const profileConditionsDescriptor = { placeholder: 'Comma separated list of domains', defaultValue: 'example.com', transformCache: {}, - transform: (optionValue) => optionValue.split(/[,;\s]+/).map(v => v.trim().toLowerCase()).filter(v => v.length > 0), + transform: (optionValue) => optionValue.split(/[,;\s]+/).map((v) => v.trim().toLowerCase()).filter((v) => v.length > 0), transformReverse: (transformedOptionValue) => transformedOptionValue.join(', '), validateTransformed: (transformedOptionValue) => (transformedOptionValue.length > 0), test: ({url}, transformedOptionValue) => _profileConditionTestDomainList(url, transformedOptionValue) diff --git a/ext/bg/js/request.js b/ext/bg/js/request.js index 3afc1506..7d73d49b 100644 --- a/ext/bg/js/request.js +++ b/ext/bg/js/request.js @@ -29,7 +29,7 @@ function requestJson(url, action, params) { } else { xhr.send(); } - }).then(responseText => { + }).then((responseText) => { try { return JSON.parse(responseText); } diff --git a/ext/bg/js/search-query-parser.js b/ext/bg/js/search-query-parser.js index 74ef32d8..c7222212 100644 --- a/ext/bg/js/search-query-parser.js +++ b/ext/bg/js/search-query-parser.js @@ -107,7 +107,7 @@ class QueryParser { } getParseResult() { - return this.parseResults.find(r => r.id === this.selectedParser); + return this.parseResults.find((r) => r.id === this.selectedParser); } async setText(text) { @@ -216,7 +216,7 @@ class QueryParser { static processParseResultForDisplay(result) { return result.map((term) => { - return term.filter(part => part.text.trim()).map((part) => { + return term.filter((part) => part.text.trim()).map((part) => { return { text: Array.from(part.text), reading: part.reading, diff --git a/ext/bg/js/settings-dictionaries.js b/ext/bg/js/settings-dictionaries.js index 177379b0..065a8abc 100644 --- a/ext/bg/js/settings-dictionaries.js +++ b/ext/bg/js/settings-dictionaries.js @@ -62,8 +62,8 @@ class SettingsDictionaryListUI { this.updateDictionaryOrder(); - const titles = this.dictionaryEntries.map(e => e.dictionaryInfo.title); - const removeKeys = Object.keys(this.optionsDictionaries).filter(key => titles.indexOf(key) < 0); + const titles = this.dictionaryEntries.map((e) => e.dictionaryInfo.title); + const removeKeys = Object.keys(this.optionsDictionaries).filter((key) => titles.indexOf(key) < 0); if (removeKeys.length > 0) { for (const key of toIterable(removeKeys)) { delete this.optionsDictionaries[key]; @@ -161,7 +161,7 @@ class SettingsDictionaryListUI { delete n.dataset.dict; $(n).modal('hide'); - const index = this.dictionaryEntries.findIndex(e => e.dictionaryInfo.title === title); + const index = this.dictionaryEntries.findIndex((e) => e.dictionaryInfo.title === title); if (index >= 0) { this.dictionaryEntries[index].deleteDictionary(); } @@ -377,7 +377,7 @@ async function onDatabaseUpdated(options) { updateMainDictionarySelect(options, dictionaries); - const {counts, total} = await utilDatabaseGetDictionaryCounts(dictionaries.map(v => v.title), true); + const {counts, total} = await utilDatabaseGetDictionaryCounts(dictionaries.map((v) => v.title), true); dictionaryUI.setCounts(counts, total); } catch (e) { dictionaryErrorsShow([e]); @@ -564,7 +564,7 @@ async function onDictionaryImport(e) { dictionaryErrorsShow(null); dictionarySpinnerShow(true); - const setProgress = percent => dictProgress.find('.progress-bar').css('width', `${percent}%`); + const setProgress = (percent) => dictProgress.find('.progress-bar').css('width', `${percent}%`); const updateProgress = (total, current) => { setProgress(current / total * 100.0); if (storageEstimate.mostRecent !== null && !storageUpdateStats.isUpdating) { diff --git a/ext/bg/js/settings-profiles.js b/ext/bg/js/settings-profiles.js index 9532e3eb..8c218e97 100644 --- a/ext/bg/js/settings-profiles.js +++ b/ext/bg/js/settings-profiles.js @@ -147,7 +147,7 @@ function profileOptionsCreateCopyName(name, profiles, maxUniqueAttempts) { let i = 0; while (true) { const newName = `${prefix}${space}${index}${suffix}`; - if (i++ >= maxUniqueAttempts || profiles.findIndex(profile => profile.name === newName) < 0) { + if (i++ >= maxUniqueAttempts || profiles.findIndex((profile) => profile.name === newName) < 0) { return newName; } if (typeof index !== 'number') { diff --git a/ext/bg/js/settings.js b/ext/bg/js/settings.js index 48026794..abe6f389 100644 --- a/ext/bg/js/settings.js +++ b/ext/bg/js/settings.js @@ -18,7 +18,7 @@ async function getOptionsArray() { const optionsFull = await apiOptionsGetFull(); - return optionsFull.profiles.map(profile => profile.options); + return optionsFull.profiles.map((profile) => profile.options); } async function formRead(options) { @@ -484,12 +484,12 @@ async function ankiDeckAndModelPopulate(options) { const deckNames = await utilAnkiGetDeckNames(); const ankiDeck = $('.anki-deck'); ankiDeck.find('option').remove(); - deckNames.sort().forEach(name => ankiDeck.append($('