All files / src/utils common-util.ts

66.32% Statements 63/95
40% Branches 12/30
90.48% Functions 19/21
65.17% Lines 58/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230                              16x   16x 16x 16x     16x 16x 16x 25x 15x 15x   10x     16x                 16x                                                           16x 3x 3x 353x   3x                 16x 1x 1x 1x 1x   1x                   16x       1x 1x 1x 1x   1x                     16x 1x 1x 1x                 16x                                                   16x 4x   4x     4x 4x                                 16x 3x 3x 2x   3x               16x 2x 1x   1x                     16x       13x       13x 13x 13x   13x 20x   13x   16x  
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
import { saveAs } from 'file-saver';
 
export class CommonUtil {
  static removeItemFromArray(item: any, items: any[]): boolean {
    Iif (item == null || items == null || items.length === 0) {
      return false;
    }
    let i = 0;
    let itemWasRemoved = false;
    while (i < items.length) {
      if (items[i] === item) {
        items.splice(i, 1);
        itemWasRemoved = true;
      } else {
        i++;
      }
    }
    return itemWasRemoved;
  }
 
  /**
   * Split a source string by the specified substring into a string array.
   *
   * @param inStr
   * @param splitMarker
   */
  static splitByString(inStr: string, splitMarker: string): string[] {
    let splitLoc = 0;
    let splitLocEnd = 0;
    let fragment = null;
    const splitMarkerLen = splitMarker.length;
    const result: string[] = [];
 
    if (
      inStr === null ||
      inStr.length === 0 ||
      splitMarker === null ||
      splitMarkerLen === 0
    ) {
      return [];
    }
    while (splitLoc !== -1) {
      splitLoc = inStr.indexOf(splitMarker);
      splitLocEnd = inStr.indexOf(splitMarker, splitLoc + 1);
      fragment = inStr.substring(splitLoc, splitLocEnd);
      result.push(fragment);
      inStr = inStr.substring(splitLocEnd + splitMarkerLen);
    }
    return result;
  }
 
  /**
   * Turn a string into a byte array.
   *
   * @param str
   */
  static str2bytes(str: string): Uint8Array {
    const bytes = new Uint8Array(str.length);
    for (let i = 0; i < str.length; i++) {
      bytes[i] = str.charCodeAt(i);
    }
    return bytes;
  }
 
  /**
   * Asynchronously read from the specified file and return as a string.
   *
   * @param fileName
   * @param reader
   */
  static async readFile(file: File, reader: FileReader): Promise<string> {
    return new Promise<string>((resolve) => {
      reader.onload = () => {
        const fileBody = reader.result;
        resolve(fileBody as string);
      };
      reader.readAsText(file);
    });
  }
 
  /**
   *  Perform an asynchronous binary read of the specified file name with the specified reader object.
   *
   * @param fileName - file to read
   * @param reader - reader object
   */
  static async readBinaryFile(
    file: File,
    reader: FileReader
  ): Promise<Int8Array> {
    return new Promise<Int8Array>((resolve) => {
      reader.onload = () => {
        const fileBody = new Int8Array(reader.result as ArrayBuffer);
        resolve(fileBody);
      };
      reader.readAsArrayBuffer(file);
    });
  }
 
  /**
   * Asynchronously write the specified file content (Blob) to the specified file name.  It will appear
   * in the user's local Downloads directory (or equivalent).
   *
   * @param fileContent
   * @param fName
   */
  static async writeFile(fileContent: Blob, fName: string): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      saveAs(fileContent, fName);
      resolve(true);
    });
  }
 
  /**
   * Convert a camel-case string into human-readable form.
   *
   * @param camelCaseString
   */
  static toDisplayable(camelCaseString: string): string {
    if (
      typeof camelCaseString === 'undefined' ||
      !camelCaseString ||
      camelCaseString.indexOf(' ') >= 0
    ) {
      return camelCaseString;
    }
    let displayableString: string = camelCaseString.charAt(0).toUpperCase();
    for (let index = 1; index < camelCaseString.length; index++) {
      const chr: string = camelCaseString.charAt(index);
      if (chr !== chr.toLowerCase()) {
        displayableString += ' ';
      }
      displayableString += chr;
    }
    return displayableString;
  }
 
  /**
   * Return a string path that fits into the width provided.  Capture as much of the leaf
   * as possible, then as much of the beginning with the remaining space.
   *
   * @param path
   * @param fieldWidth
   */
  static extractDisplayPath(path: string, fieldWidth: number): string {
    const MAX_PATH_WIDTH = fieldWidth - 4; // account for length of ellipsis
 
    Iif (!path || MAX_PATH_WIDTH <= 0) {
      return '';
    }
    Eif (path.length <= MAX_PATH_WIDTH) {
      return path;
    }
    const segmentedPath = path.split('/');
    const leaf = '/' + segmentedPath[segmentedPath.length - 1];
    if (leaf.length >= MAX_PATH_WIDTH) {
      return leaf.substr(0, MAX_PATH_WIDTH);
    }
    const delta = MAX_PATH_WIDTH - leaf.length;
    return path.substr(0, delta) + '...' + leaf;
  }
 
  /**
   * Use the JSON utility to translate the specified buffer into a JSON buffer - then replace any
   * non-ascii character encodings with unicode escape sequences.
   *
   * @param buffer
   */
  static sanitizeJSON(buffer: string): string {
    let jsonBuffer = JSON.stringify(buffer);
    jsonBuffer = jsonBuffer.replace(/[\u007F-\uFFFF]/g, function (chr) {
      return '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).substr(-4);
    });
    return jsonBuffer;
  }
 
  /**
   * Restrict JSON parsing to the document management service.
   *
   * @param buffer
   */
  static objectize(buffer: any): any {
    if (typeof buffer === 'string') {
      return JSON.parse(buffer);
    } else {
      return buffer;
    }
  }
 
  /**
   * Returns the given URL with the query parameters replaced with the new
   * values.
   *
   * @param url - the URL
   * @param parameters - the new parameters to set
   */
  static urlWithParameters(
    url: string,
    parameters: string[][] | Record<string, string> | string | URLSearchParams
  ): string {
    const newUrl = new URL(url);
    // we can't invoke delete in a loop over uri.searchParams, results
    // become unreliable, so we gather the keys for deletion, also the
    // URLSearchParams.keys() method is not available for some reason
    const keys: string[] = [];
    newUrl.searchParams.forEach((_, k) => keys.push(k));
    keys.forEach((k) => newUrl.searchParams.delete(k));
 
    const params = new URLSearchParams(parameters);
    params.forEach((v, k) => newUrl.searchParams.append(k, v));
 
    return newUrl.toString();
  }
}