File

src/lib/util/utils.ts

Index

Methods

Methods

Static arrayToObject
arrayToObject(arr: [], keyProperty?: string | , valueProperty?: string | )
Parameters :
Name Type Optional Default value
arr [] no []
keyProperty string | yes
valueProperty string | yes
Returns : any
Static buildUri
buildUri(uri: string, params: literal type)

Utility method for adding parameters to a given URI.

Parameters :
Name Type Optional Description
uri string no

The uri string to attach the parameters to

params literal type no

The object containing parameters to be appended

Returns : string

the given uri extended by the given parameters + remove empty parameters

Static catch
catch(callback?: (undefined) => void, name?: string, message?: string, skipNotification?: boolean)

Use on Observable.catch !!! ng-packagr issues

Parameters :
Name Type Optional
callback function yes
name string yes
message string yes
skipNotification boolean yes
Returns : (error: any) => any

(error) => Observable

Static catchSkip
catchSkip(skipNotification?: (undefined) => void, callback?: (undefined) => void, name?: string, message?: string)

Use on Observable.catch with specific skipNotification function !!! ng-packagr issues 696

Parameters :
Name Type Optional
skipNotification function yes
callback function yes
name string yes
message string yes
Returns : (error: any) => any
Static empty
empty(callback?: (undefined) => void)

Use on Observable.catch or Observable.subscribe to return empty value ng-packagr issues 696

Parameters :
Name Type Optional
callback function yes
Returns : (error: any) => any

(error) => Observable

Static encodeFileName
encodeFileName(filename: string)

Encode a filename safe for sending chars beyond ASCII-7bit using quoted printable encoding.

Parameters :
Name Type Optional Description
filename string no

The file name

Returns : string

The quoted printable filename

Static formatMailTo
formatMailTo(value: FormatedMailTo, isEmail: boolean)
Parameters :
Name Type Optional
value FormatedMailTo no
isEmail boolean no
Returns : FormatedMailTo
Static formDataParse
formDataParse(str: string)
Parameters :
Name Type Optional
str string no
Returns : any
Static formDataStringify
formDataStringify(o: any)
Parameters :
Name Type Optional
o any no
Returns : string
Static getBaseHref
getBaseHref()
Returns : any
Static getProperty
getProperty(object: any, key: string)
Parameters :
Name Type Optional Default value
object any no
key string no ''
Returns : any

any

Static getTimezoneOffset
getTimezoneOffset()

Get the TimeZone Offsest as ISO String.

Returns : string
Static isVisible
isVisible(elem: any)

Checks if element is visible

Parameters :
Name Type Optional
elem any no
Returns : boolean

boolean

Static logError
logError(callback?: (undefined) => void, name?: string, message?: string, skipNotification: )

Use on Observable.subscribe only if you want to skip notification / toast!!!

Parameters :
Name Type Optional Default value
callback function yes
name string yes
message string yes
skipNotification no true
Returns : (error: any) => never

(error) => void

Static sortValues
sortValues(key: string, order: string, locales?: string | string[], options?: Intl.CollatorOptions)

Sorts An Array of Object by given key See ng-packagr issues 696

Parameters :
Name Type Optional Default value
key string no ''
order string no 'asc'
locales string | string[] yes
options Intl.CollatorOptions yes
Returns : (a: any, b: any) => number

(a: any, b: any) => number

Static throw
throw(callback?: (undefined) => void, name?: string, message?: string, skipNotification?: boolean)

Use on Observable.subscribe !!! ng-packagr issues

Parameters :
Name Type Optional
callback function yes
name string yes
message string yes
skipNotification boolean yes
Returns : (error: any) => never

(error) => void

Static truncateString
truncateString(str: , num: , ending: string)

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending ot whats provided.

Parameters :
Name Type Optional Default value
str no
num no
ending string no '...'
Returns : any
Static uniqBy
uniqBy(items: any[], property: string)
Parameters :
Name Type Optional
items any[] no
property string no
Returns : any
Static uuid
uuid()

Creates a unique identifier.

Returns : string

A Universally Unique Identifier

import {EMPTY as observableEmpty, throwError as observableThrowError} from 'rxjs';
import {EoError} from '../model/eo-error.model';
import {RangeValue} from '../model/range-value.model';
import moment from 'moment';

export type FormatedMailTo = string | string[];
export class Utils {

  private static PREF_RANGEVALUE = 'RangeValue';

  public static uniqBy(items: any[], property: string) {
    const a: {[key: string]: any} = {};
    items.forEach(i => a[i[property]] = i);
    return Object.keys(a).map(k => a[k]) 
  }

  /**
   * Utility method for adding parameters to a given URI.
   *
   * @param uri The uri string to attach the parameters to
   * @param params The object containing parameters to be appended
   * @returns the given uri extended by the given parameters + remove empty parameters
   */
  public static buildUri(uri: string, params: {}): string {
    const q = Object.keys(params)
      .filter(k => params[k] || params[k] === 0 || params[k] === false)
      .map(k => k + '=' + encodeURIComponent(params[k])).join('&');
    return uri + (q ? '?' + q : '');
  }

  /**
   * Creates a unique identifier.
   * @returns A Universally Unique Identifier
   */
  public static uuid(): string {
    return Utils._p8() + Utils._p8(true) + Utils._p8(true) + Utils._p8();
  }

  /**
   * Encode a filename safe for sending chars beyond ASCII-7bit using quoted printable encoding.
   *
   * @param filename The file name
   * @returns The quoted printable filename
   */
  public static encodeFileName(filename: string): string {
    const fileName = Utils.encodeToQuotedPrintable(Utils.encodeToUtf8(filename)).replace(/_/g, '=5F')
    return `=?UTF-8?Q?${fileName}?=`;
  }

  /**
   *
   * @param boolean s
   * @return string
   */
  private static _p8(s?: boolean): string {
    const p = (Math.random().toString(16) + '000000000').substr(2, 8);
    return s ? `-${p.substr(0, 4)}-${p.substr(4, 4)}` : p;
  }

  /**
   * Converts a javascript text to the utf-8 converted variant.
   * See [unicode]{@link http://thlist.onlinehome.de/thomas_homepage/unicode/UTF-8%20Konvertierung%20mittels%20JavaScript.htm} for reference
   *
   * @param rawinput The input string
   * @returns The utf-8 converted string
   */
  private static encodeToUtf8(rawinput) {
    /**
     * Normalize line breaks
     */
    rawinput = rawinput.replace(/\r\n/g, '\n');
    let utfreturn = '';
    for (let n = 0; n < rawinput.length; n++) {
      /**
       * Unicode for current char
       */
      const c = rawinput.charCodeAt(n);
      if (c < 128) {
        /**
         * All chars range 0-127 => 1byte
         */
        utfreturn += String.fromCharCode(c);
      } else if ((c > 127) && (c < 2048)) {
        /**
         * All chars range from 127 to 2047 => 2byte
         */
        utfreturn += String.fromCharCode((c >> 6) | 192);
        utfreturn += String.fromCharCode((c & 63) | 128);
      } else {
        /**
         * All chars range from 2048 to 66536 => 3byte
         */
        utfreturn += String.fromCharCode((c >> 12) | 224);
        utfreturn += String.fromCharCode(((c >> 6) & 63) | 128);
        utfreturn += String.fromCharCode((c & 63) | 128);
      }
    }
    return utfreturn;
  }

  /**
   * See [quoted-printable]{@link https://github.com/mathiasbynens/quoted-printable/blob/master/quoted-printable.js}
   **/
  private static quotedPrintable(symbol) {
    if (symbol > '\xFF') {
      throw RangeError('`encodeToQuotedPrintable` expects extended ASCII input only. Missing prior UTF-8 encoding?');
    }
    const codePoint = symbol.charCodeAt(0);
    const hexadecimal = codePoint.toString(16).toUpperCase();
    return '=' + ('0' + hexadecimal).slice(-2);
  }

  /**
   * Encode symbols that are definitely unsafe (i.e. unsafe in any context). The regular expression describes these unsafe symbols.
   *
   * @param rawinput Input string to be encoded
   * @returns The encoded string
   */
  private static encodeToQuotedPrintable(rawinput): string {
    const encoded = rawinput.replace(/[\0-\b\n-\x1F=\x7F-\uD7FF\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF]/g, this.quotedPrintable);
    return encoded;
  }

  /**
   * Sorts An Array of Object by given key
   * See [ng-packagr issues 696]{@link https://github.com/dherges/ng-packagr/issues/696}
   *
   * @param key
   * @param order
   * @param locales
   * @param options
   * @returns (a: any, b: any) => number
   */
  public static sortValues(key = '', order = 'asc', locales?: string | string[], options?: Intl.CollatorOptions) {
    const f = (a: any, b: any) => {
      let comparison: number;
      const varA = Utils.getProperty(a, key) ?? a['value'];
      const varB = Utils.getProperty(b, key) ?? a['value'];
      if (typeof varA === 'number' && typeof varB === 'number') {
        comparison = varA - varB;
      } else {
        const stringA = varA || varA === 0 ? varA.toString() : '';
        const stringB = varB || varB === 0 ? varB.toString() : '';
        comparison = stringA.localeCompare(stringB, locales, options);
      }
      return order === 'desc' ? -comparison : comparison;
    };
    return f;
  }

  /**
   * [ng-packagr issues 696]{@link https://github.com/dherges/ng-packagr/issues/696}
   *
   * @param object
   * @param string key
   * @returns any
   */
  public static getProperty(object: any, key = ''): any {
    const f = key ? key.split('.').reduce((o, k) => (o || {})[k], object) : object;
    return f;
  }

  /**
   * Use on Observable.catch or Observable.subscribe to return empty value
   * [ng-packagr issues 696]{@link https://github.com/dherges/ng-packagr/issues/696}
   *
   * @param (error) => any callback
   * @returns (error) => Observable<never>
   */
  public static empty(callback?: (error) => any) {
    const f = (error) => {
      return observableEmpty;
    };
    return f;
  }

  /**
   * Use on Observable.catch with specific skipNotification function !!!
   * [ng-packagr issues 696]{@link https://github.com/dherges/ng-packagr/issues/696}
   *
   * @param skipNotification
   * @param callback
   * @param name
   * @param message
   */
  public static catchSkip(skipNotification?: (error) => any, callback?: (error) => any, name?: string, message?: string) {
    const f = (error) => {
      const _error = callback && callback(error);
      const _skipNotification = skipNotification && skipNotification(error);
      return observableThrowError(new EoError(_error instanceof Error ? _error : error, name, message, _skipNotification));
    };
    return f;
  }

  /**
   * Use on Observable.catch !!!
   * [ng-packagr issues]{@link https://github.com/dherges/ng-packagr/issues/696}
   *
   * @param callback
   * @param name
   * @param message
   * @param skipNotification
   * @return (error) => Observable<never>
   */
  public static catch(callback?: (error) => any, name?: string, message?: string, skipNotification?: boolean) {
    const f = (error) => {
      const _error = callback && callback(error);
      return observableThrowError(new EoError(_error instanceof Error ? _error : error, name, message, skipNotification));
    };
    return f;
  }

  /**
   * Use on Observable.subscribe !!!
   * [ng-packagr issues]{@link https://github.com/dherges/ng-packagr/issues/696}
   *
   * @param callback
   * @param name
   * @param message
   * @param skipNotification
   * @return (error) => void
   */
  public static throw(callback?: (error) => any, name?: string, message?: string, skipNotification?: boolean) {
    const f = (error) => {
      const _error = callback && callback(error);
      throw new EoError(_error instanceof Error ? _error : error, name, message, skipNotification);
    };
    return f;
  }

  /**
   * Use on Observable.subscribe only if you want to skip notification / toast!!!
   *
   * @param callback
   * @param name
   * @param message
   * @param skipNotification
   * @return (error) => void
   */
  public static logError(callback?: (error) => any, name?: string, message?: string, skipNotification = true) {
    return Utils.throw(callback, name, message, skipNotification);
  }

  /**
   * Checks if element is visible
   *
   * @param elem
   * @return boolean
   */
  public static isVisible(elem: any): boolean {
    return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
  }

  public static getBaseHref() {
    return document.getElementsByTagName('base')[0].getAttribute('href');
  }

  /**
   *
   * Truncate a string (first argument) if it is longer than the given maximum string length (second argument).
   * Return the truncated string with a ... ending ot whats provided.
   *
   * @param string str
   * @param number num
   * @returns
   */
  public static truncateString(str, num, ending = '...') {
    if (str.length > num) {
      if (num > 3) {
        num -= 3;
      }
      str = `${str.substring(0, num)}${ending}`;
    }
    return str;
  };

  /**
   * Get the TimeZone Offsest as ISO String.
   *
   * @returns
   */
  public static getTimezoneOffset(): string {
    return moment().format('Z');
  }

  public static formatMailTo(value: FormatedMailTo, isEmail: boolean): FormatedMailTo {
    if (isEmail && !!value) {
      return (Array.isArray(value)) ? value.join().replace(/,/g, '; ') : value.replace(/,/g, '; ');
    }
    return value;
  }

  public static arrayToObject(arr = [], keyProperty?: string | ((o: any) => string), valueProperty?: string | ((o: any) => any)) {
    const key = typeof keyProperty === 'string' ? (o: any) => o[keyProperty] : keyProperty;
    const value = typeof valueProperty === 'string' ? (o: any) => o[valueProperty] : valueProperty;
    return arr.reduce((acc, cur, i) => {
      acc[key ? key(cur) : i] = value ? value(cur) : cur;
      return acc;
    }, {});
  }

  public static formDataStringify(o: any): string {
    const f = (key, value) => {
      if (value instanceof RangeValue) {
        return `/${Utils.PREF_RANGEVALUE}(${JSON.stringify(value)})/`;
      }
      return value;
    };
    return JSON.stringify(o, f);
  }

  public static formDataParse(str: string): any {
    const f = (key, value) => {
      if (
        typeof value === 'string' &&
        value.startsWith(`/${Utils.PREF_RANGEVALUE}(`) &&
        value.endsWith(')/')
      ) {
        value = value.substring(Utils.PREF_RANGEVALUE.length + 2, value.length - 2);
        const parsed = JSON.parse(value);

        return new RangeValue(parsed.operator, parsed.firstValue, parsed.secondValue);
      }
      return value;
    };
    return JSON.parse(str, f);
  }
}

results matching ""

    No results matching ""