Эх сурвалжийг харах

[ui-core] replace indexOf with more readable util functions (#4276)

Ram Prasad Agarwal 2 сар өмнө
parent
commit
d983969d3f

+ 1 - 1
desktop/core/src/desktop/js/api/utils.ts

@@ -154,7 +154,7 @@ const notifyError = <T>(
 ): void => {
   if (!options || !options.silenceErrors) {
     logError(response);
-    if (message.indexOf('AuthorizationException') === -1) {
+    if (!message.includes('AuthorizationException')) {
       huePubSub.publish<HueAlert>(GLOBAL_ERROR_TOPIC, { message });
     }
   }

+ 7 - 9
desktop/core/src/desktop/js/apps/editor/components/aceEditor/AceLocationHandler.ts

@@ -387,9 +387,9 @@ export default class AceLocationHandler implements Disposable {
               token !== null &&
               !token.notFound &&
               token.parseLocation &&
-              ['alias', 'whereClause', 'limitClause', 'selectList'].indexOf(
+              !['alias', 'whereClause', 'limitClause', 'selectList'].includes(
                 token.parseLocation.type
-              ) === -1
+              )
             ) {
               markLocation(token.parseLocation);
             }
@@ -441,9 +441,9 @@ export default class AceLocationHandler implements Disposable {
         if (
           token &&
           ((token.parseLocation &&
-            ['alias', 'whereClause', 'limitClause', 'selectList'].indexOf(
+            !['alias', 'whereClause', 'limitClause', 'selectList'].includes(
               token.parseLocation.type
-            ) === -1) ||
+            )) ||
             token.syntaxError)
         ) {
           let range: Ace.Range | undefined = undefined;
@@ -768,7 +768,7 @@ export default class AceLocationHandler implements Disposable {
   clearMarkedErrors(type?: string): void {
     const markers = this.editor.getSession().$backMarkers;
     for (const markerId in markers) {
-      if (markers[markerId].clazz.indexOf('hue-ace-syntax-' + (type || '')) === 0) {
+      if (markers[markerId].clazz.startsWith('hue-ace-syntax-' + (type || ''))) {
         markers[markerId].dispose();
       }
     }
@@ -1180,8 +1180,7 @@ export default class AceLocationHandler implements Disposable {
                 const nameLower = entry.name.toLowerCase();
                 if (
                   nameLower === tokenValLower ||
-                  (tokenValLower.indexOf('`') === 0 &&
-                    tokenValLower.replace(/`/g, '') === nameLower)
+                  (tokenValLower.startsWith('`') && tokenValLower.replace(/`/g, '') === nameLower)
                 ) {
                   // Break if found
                   this.verifyThrottle = window.setTimeout(verify, VERIFY_DELAY);
@@ -1323,8 +1322,7 @@ export default class AceLocationHandler implements Disposable {
             return;
           }
           if (
-            ['statement', 'selectList', 'whereClause', 'limitClause'].indexOf(location.type) !==
-              -1 ||
+            ['statement', 'selectList', 'whereClause', 'limitClause'].includes(location.type) ||
             ((location.type === 'table' || location.type === 'column') &&
               typeof location.identifierChain === 'undefined')
           ) {

+ 1 - 1
desktop/core/src/desktop/js/apps/editor/components/aceEditor/acePredict.ts

@@ -141,7 +141,7 @@ export const attachPredictTypeahead = (
         activePredict &&
         (!editorText.length ||
           activePredict.text === editorText ||
-          activePredict.text.indexOf(editorText) !== 0)
+          !activePredict.text.startsWith(editorText))
       ) {
         removeActivePredict();
       }

+ 8 - 9
desktop/core/src/desktop/js/apps/editor/components/aceEditor/autocomplete/AutocompleteResults.ts

@@ -309,7 +309,7 @@ class AutocompleteResults {
     }
 
     const foundVarRef = this.parseResult.colRef.identifierChain.some(
-      identifier => typeof identifier.name !== 'undefined' && identifier.name.indexOf('${') === 0
+      identifier => typeof identifier.name !== 'undefined' && identifier.name.startsWith('${')
     );
 
     if (!foundVarRef) {
@@ -1007,10 +1007,9 @@ class AutocompleteResults {
           complexExtras
         ) {
           complexExtras.forEach(field => {
-            const fieldType =
-              field.type.indexOf('<') !== -1
-                ? field.type.substring(0, field.type.indexOf('<'))
-                : field.type;
+            const fieldType = field.type.includes('<')
+              ? field.type.substring(0, field.type.indexOf('<'))
+              : field.type;
             columnSuggestions.push({
               value: field.name,
               meta: fieldType,
@@ -2039,7 +2038,7 @@ class AutocompleteResults {
       } else if (tables[i].identifierChain.length === 1) {
         tablePath = this.activeDatabase + '.' + tables[i].identifierChain[0].name;
       }
-      if (path.indexOf(tablePath) === 0) {
+      if (path.startsWith(tablePath)) {
         path = path.substring(tablePath.length + 1);
         if (tables[i].alias) {
           path = tables[i].alias + '.' + path;
@@ -2116,12 +2115,12 @@ class AutocompleteResults {
     });
 
     for (let i = 0; i < aliases.length; i++) {
-      if (qualifiedIdentifier.toLowerCase().indexOf(aliases[i].qualifiedName) === 0) {
+      if (qualifiedIdentifier.toLowerCase().startsWith(aliases[i].qualifiedName)) {
         return aliases[i].alias + qualifiedIdentifier.substring(aliases[i].qualifiedName.length);
       } else if (
         qualifiedIdentifier
           .toLowerCase()
-          .indexOf(this.activeDatabase.toLowerCase() + '.' + aliases[i].qualifiedName) === 0
+          .startsWith(this.activeDatabase.toLowerCase() + '.' + aliases[i].qualifiedName)
       ) {
         return (
           aliases[i].alias +
@@ -2133,7 +2132,7 @@ class AutocompleteResults {
     }
 
     if (
-      qualifiedIdentifier.toLowerCase().indexOf(this.activeDatabase.toLowerCase()) === 0 &&
+      qualifiedIdentifier.toLowerCase().startsWith(this.activeDatabase.toLowerCase()) &&
       !tablesHasDefaultDatabase
     ) {
       return qualifiedIdentifier.substring(this.activeDatabase.length + 1);

+ 1 - 1
desktop/core/src/desktop/js/apps/editor/execution/executionLogs.ts

@@ -63,7 +63,7 @@ export default class ExecutionLogs {
       jobs: this.jobs
     });
 
-    if (logDetails.logs.indexOf('Unable to locate') === -1 || logDetails.isFullLogs) {
+    if (!logDetails.logs.includes('Unable to locate') || logDetails.isFullLogs) {
       this.fullLog = logDetails.logs;
     } else {
       this.fullLog += '\n' + logDetails.logs;

+ 9 - 9
desktop/core/src/desktop/js/apps/editor/execution/sqlExecutable.test.ts

@@ -101,12 +101,12 @@ describe('sqlExecutable.js', () => {
 
     jest.spyOn(ApiUtils, 'post').mockImplementation((url: string): CancellablePromise<unknown> => {
       currentApiHit++;
-      if (url.indexOf('/create_session') !== -1) {
+      if (url.includes('/create_session')) {
         createSessionApiHit = currentApiHit;
         return new CancellablePromise<unknown>(resolve => {
           resolve({ session: { type: 'foo' } });
         });
-      } else if (url.indexOf('/execute') !== -1) {
+      } else if (url.includes('/execute')) {
         executeApiHit = currentApiHit;
         expect(url).toContain('/execute/impala');
         return new CancellablePromise<unknown>(resolve => {
@@ -117,11 +117,11 @@ describe('sqlExecutable.js', () => {
             history_parent_uuid: 'some_history_parent_uuid'
           });
         });
-      } else if (url.indexOf('/check_status') !== -1) {
+      } else if (url.includes('/check_status')) {
         checkStatusApiHit = currentApiHit;
         statusResolve({ query_status: { status: ExecutionStatus.available } });
         return statusPromise;
-      } else if (url.indexOf('/get_logs') !== -1) {
+      } else if (url.includes('/get_logs')) {
         getLogsApiHit = currentApiHit;
         logsResolve({ status: 0, logs: '' });
         return logsPromise;
@@ -153,10 +153,10 @@ describe('sqlExecutable.js', () => {
     });
 
     jest.spyOn(ApiUtils, 'post').mockImplementation((url: string): CancellablePromise<unknown> => {
-      if (url.indexOf('/create_session') !== -1) {
+      if (url.includes('/create_session')) {
         return CancellablePromise.resolve({ session: { type: 'foo' } });
       }
-      if (url.indexOf('/execute') !== -1) {
+      if (url.includes('/execute')) {
         expect(url).toContain('/execute/impala');
         return CancellablePromise.resolve({
           handle: {
@@ -167,17 +167,17 @@ describe('sqlExecutable.js', () => {
           history_parent_uuid: 'some_history_parent_uuid'
         });
       }
-      if (url.indexOf('/check_status') !== -1) {
+      if (url.includes('/check_status')) {
         statusResolve({
           query_status: { status: ExecutionStatus.available, has_result_set: true }
         });
         return statusPromise;
       }
-      if (url.indexOf('/get_logs') !== -1) {
+      if (url.includes('/get_logs')) {
         return CancellablePromise.resolve({ status: 0, logs: '' });
       }
 
-      if (url.indexOf('/fetch_result_data')) {
+      if (url.includes('/fetch_result_data')) {
         return CancellablePromise.resolve({});
       }
       fail('fail for URL: ' + url);

+ 6 - 8
desktop/core/src/desktop/js/apps/jobBrowser/knockout/JobBrowserViewModel.js

@@ -50,13 +50,13 @@ export default class JobBrowserViewModel {
 
     this.availableInterfaces = ko.pureComputed(() => {
       const isDialectEnabled = dialect =>
-        this.appConfig()?.editor?.interpreter_names?.indexOf(dialect) >= 0;
+        this.appConfig()?.editor?.interpreter_names?.includes(dialect);
 
       const historyInterfaceCondition = () => window.ENABLE_HISTORY_V2;
 
       const jobsInterfaceCondition = () =>
         !getLastKnownConfig().has_computes &&
-        this.appConfig()?.browser?.interpreter_names.indexOf('yarn') !== -1 &&
+        this.appConfig()?.browser?.interpreter_names?.includes('yarn') &&
         (!this.cluster() || this.cluster().type.indexOf('altus') === -1);
 
       const dataEngInterfaceCondition = () => this.cluster()?.type === 'altus-de';
@@ -80,15 +80,13 @@ export default class JobBrowserViewModel {
 
       const livyInterfaceCondition = () =>
         !this.isMini() &&
-        this.appConfig()?.editor &&
-        (this.appConfig().editor.interpreter_names.indexOf('pyspark') !== -1 ||
-          this.appConfig().editor.interpreter_names.indexOf('sparksql') !== -1);
-
+        (this.appConfig()?.editor?.interpreter_names?.includes('pyspark') ||
+          this.appConfig()?.editor?.interpreter_names?.includes('sparksql'));
       const queryInterfaceCondition = () =>
         window.ENABLE_QUERY_BROWSER &&
         !getLastKnownConfig().has_computes &&
-        this.appConfig()?.editor.interpreter_names.indexOf('impala') !== -1 &&
-        (!this.cluster() || this.cluster().type.indexOf('altus') === -1);
+        this.appConfig()?.editor?.interpreter_names?.includes('impala') &&
+        (!this.cluster()?.type?.includes('altus'));
 
       const queryHiveInterfaceCondition = () => {
         return window.ENABLE_HIVE_QUERY_BROWSER && !getLastKnownConfig().has_computes;

+ 1 - 1
desktop/core/src/desktop/js/catalog/DataCatalogEntry.ts

@@ -1542,7 +1542,7 @@ export default class DataCatalogEntry {
    */
   getType(): string {
     let type = this.getRawType();
-    if (type.indexOf('<') !== -1) {
+    if (type.includes('<')) {
       type = type.substring(0, type.indexOf('<'));
     }
     return type.toLowerCase();

+ 2 - 2
desktop/core/src/desktop/js/catalog/api.ts

@@ -297,7 +297,7 @@ export const fetchPartitions = ({
         if (
           errorResponse.response &&
           errorResponse.response.data &&
-          errorResponse.response.data.indexOf('is not partitioned') !== -1
+          errorResponse.response.data.includes('is not partitioned')
         ) {
           resolve({
             hueTimestamp: Date.now(),
@@ -583,7 +583,7 @@ export const fetchSourceMetadata = ({
           !!response &&
           response.status === 0 &&
           response.code === 500 &&
-          (message.indexOf('Error 10001') !== -1 || message.indexOf('AnalysisException') !== -1);
+          (message.includes('Error 10001') || message.includes('AnalysisException'));
 
         adjustedResponse.hueTimestamp = Date.now();
 

+ 2 - 2
desktop/core/src/desktop/js/catalog/dataCatalog.ts

@@ -334,7 +334,7 @@ export class DataCatalog {
       computeName: compute.name
     });
     Object.keys(this.entries).forEach(key => {
-      if (key.indexOf(keyPrefix) === 0) {
+      if (key.startsWith(keyPrefix)) {
         delete this.entries[key];
       }
     });
@@ -343,7 +343,7 @@ export class DataCatalog {
     try {
       const keys = await this.store.keys();
       keys.forEach(key => {
-        if (key.indexOf(keyPrefix) === 0) {
+        if (key.startsWith(keyPrefix)) {
           deletePromises.push(this.store.removeItem(key));
         }
       });

+ 1 - 1
desktop/core/src/desktop/js/sql/reference/sqlUdfRepository.ts

@@ -269,7 +269,7 @@ huePubSub.subscribe(
   async (details: { connector: Connector; callback: () => void }) => {
     await clearUdfCache(details.connector);
     Object.keys(mergedUdfPromises).forEach(key => {
-      if (key === details.connector.id || key.indexOf(details.connector.id + '_') === 0) {
+      if (key === details.connector.id || key.startsWith(details.connector.id + '_')) {
         delete mergedUdfPromises[key];
       }
     });

+ 2 - 6
desktop/core/src/desktop/js/sql/reference/typeUtils.ts

@@ -23,7 +23,7 @@ import { TYPE_CONVERSION as SPARKSQL_TYPE_CONVERSION } from './sparksql/typeConv
 const stripPrecision = (types: string[]): string[] => {
   const result: string[] = [];
   types.forEach(type => {
-    if (type.indexOf('(') > -1) {
+    if (type.includes('(')) {
       result.push(type.substring(0, type.indexOf('(')));
     } else {
       result.push(type);
@@ -57,11 +57,7 @@ export const matchesType = (
     return true;
   }
   const actualTypes = stripPrecision(actualRawTypes);
-  if (
-    actualTypes.indexOf('ARRAY') !== -1 ||
-    actualTypes.indexOf('MAP') !== -1 ||
-    actualTypes.indexOf('STRUCT') !== -1
-  ) {
+  if (['ARRAY', 'MAP', 'STRUCT'].some(type => actualTypes.includes(type))) {
     return true;
   }
   const conversionTable = getTypeConversion(dialect);

+ 2 - 3
desktop/core/src/desktop/js/sql/sqlUtils.ts

@@ -42,8 +42,7 @@ const autocompleteFilter = (filter: string, entries: Suggestion[]): Suggestion[]
     if (foundIndex !== -1) {
       if (
         foundIndex === 0 ||
-        (suggestion.filterValue &&
-          suggestion.filterValue.toLowerCase().indexOf(lowerCaseFilter) === 0)
+        (suggestion.filterValue && suggestion.filterValue.toLowerCase().startsWith(lowerCaseFilter))
       ) {
         suggestion.filterWeight = 3;
       } else {
@@ -52,7 +51,7 @@ const autocompleteFilter = (filter: string, entries: Suggestion[]): Suggestion[]
     } else if (
       suggestion.details &&
       (<CommentDetails>suggestion.details).comment &&
-      lowerCaseFilter.indexOf(' ') === -1
+      !lowerCaseFilter.includes(' ')
     ) {
       foundIndex = (<CommentDetails>suggestion.details).comment
         .toLowerCase()

+ 2 - 2
desktop/core/src/desktop/js/utils/html/getFileBrowseButton.ts

@@ -64,7 +64,7 @@ const getFileBrowseButton = (
       if (inputElement.data('fullPath')) {
         initialPath = inputElement.data('fullPath');
       }
-      if (initialPath.indexOf('hdfs://') > -1) {
+      if (initialPath.includes('hdfs://')) {
         initialPath = initialPath.substring(7);
       }
 
@@ -152,7 +152,7 @@ const getFileBrowseButton = (
       ) {
         inputElement.data('fullPath', filePath);
         inputElement.attr('data-original-title', filePath);
-        if (filePath.indexOf(allBindingsAccessor().filechooserOptions.deploymentDir) === 0) {
+        if (filePath.startsWith(allBindingsAccessor().filechooserOptions.deploymentDir)) {
           filePath = filePath.substr(
             allBindingsAccessor().filechooserOptions.deploymentDir.length + 1
           );

+ 2 - 2
desktop/core/src/desktop/js/utils/html/onHueLinkClick.ts

@@ -18,10 +18,10 @@ import { hueWindow } from 'types/types';
 import huePubSub from 'utils/huePubSub';
 
 const onHueLinkClick = (event: Event, url: string, target?: string): void => {
-  if (url.indexOf('http') === 0) {
+  if (url.startsWith('http')) {
     window.open(url, target);
   } else {
-    const prefix = (<hueWindow>window).HUE_BASE_URL + '/hue' + (url.indexOf('/') === 0 ? '' : '/');
+    const prefix = (<hueWindow>window).HUE_BASE_URL + '/hue' + (url.startsWith('/') ? '' : '/');
     if (target) {
       window.open(prefix + url, target);
     } else if (

+ 1 - 1
desktop/core/src/desktop/js/utils/string/parseHivePseudoJson.ts

@@ -21,7 +21,7 @@ const parseHivePseudoJson = (pseudoJson: string): { [key: string]: string } => {
   if (pseudoJson && pseudoJson.length > 2) {
     const splits = pseudoJson.substring(1, pseudoJson.length - 1).split(', ');
     splits.forEach(part => {
-      if (part.indexOf('=') > -1) {
+      if (part.includes('=')) {
         parsedParams[part.split('=')[0]] = part.split('=')[1];
       }
     });

+ 2 - 2
desktop/core/src/desktop/js/utils/url/changeURL.ts

@@ -32,10 +32,10 @@ const changeURL = (
   const hashSplit = newURL.split('#');
   const hueBaseUrl = (<hueWindow>window).HUE_BASE_URL;
   const base =
-    hueBaseUrl && hashSplit[0].length && hashSplit[0].indexOf(hueBaseUrl) !== 0 ? hueBaseUrl : '';
+    hueBaseUrl && hashSplit[0].length && !hashSplit[0].startsWith(hueBaseUrl) ? hueBaseUrl : '';
   let newUrl = base + hashSplit[0];
   if (extraSearch) {
-    newUrl += (newUrl.indexOf('?') === -1 ? '?' : '&') + extraSearch;
+    newUrl += (newUrl.includes('?') ? '&' : '?') + extraSearch;
   }
   if (hashSplit.length > 1) {
     //the foldername may contain # , so create substring ignoring first #

+ 1 - 1
desktop/core/src/desktop/js/utils/url/changeURLParameter.ts

@@ -35,7 +35,7 @@ const changeURLParameter = (param: string, value: string | null): void => {
   } else {
     newSearch =
       window.location.search +
-      (value ? (window.location.search.indexOf('?') > -1 ? '&' : '?') + param + '=' + value : '');
+      (value ? (window.location.search.includes('?') ? '&' : '?') + param + '=' + value : '');
   }
 
   if (newSearch === '?') {