File

app/core/services/util-service/util.service.ts

Index

Properties
Methods

Constructor

constructor(document, constants: ConstantsService)
Parameters :
Name Type Optional
document No
constants ConstantsService No

Methods

Public extract
extract(...args: any[])
Parameters :
Name Type Optional
args any[] No
Returns : any
formatFilesize
formatFilesize(fileSizeInBytes: number)
Parameters :
Name Type Optional
fileSizeInBytes number No
Returns : string
Public getComponentId
getComponentId(component)
Parameters :
Name Optional
component No
Returns : any
Public getCurrentDate
getCurrentDate(separator: string)

Returns the current date as a string in format YYYYxMMxDD with x as an optional separator.

Parameters :
Name Type Optional Default value
separator string No ''
Returns : string
Public loadScript
loadScript(url: string)
Parameters :
Name Type Optional
url string No
Returns : Promise<any>
Public partiallyApplyExtract
partiallyApplyExtract(...args: any[])
Parameters :
Name Type Optional
args any[] No
Returns : (...args2: {}) => any
Public pickOneFromArray
pickOneFromArray(array, predicate)

Takes in an array and a predicate, and returns the first array element matching the predicate, removing it from the array.

Parameters :
Name Optional
array No
predicate No
Returns : any

Properties

scripts
Type : []
Default value : []
import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { ConstantsService } from 'src/app/shared/constants/constants.service';

// DID WE ADD THE BUG FIXES MADE IN VSM HERE???

@Injectable()
export class UtilService {

	scripts = [];

	constructor(@Inject(DOCUMENT) private document, private constants: ConstantsService) { }



	/*
		The 'extract' function allows you to easily pull out data nested deep within complicated JSON structures, in one function call.
		If the requested data can not be reached, the function will return UNDEFINED. This mitigates the need for "null pointer checks"
		for every step of the lookup chain.

		It also supports array lookup, both by index, and by a filtering function.

		You can activate tracing for debugging purposes, by adding 'TRACE' as the first argument.


		USAGE EXAMPLES THAT DEMONSTRATE FUNCTIONALITY
		---------------------------------------------

		extract( person, 'data', 'firstName' );

		Equivalent to person.data.firstName, except it will not throw and exception if 'person' or 'person.data' returns undefined.


		extract( '(TRACE)', person, 'data', 'firstName' );

		The same as the previous call, except with 'TRACE' added as first parameter. This activates tracing,
		so you can see where in the chain your 'extract' call fails.


		extract( person, 'items', [0], 'value' );

		Equivalent to person.items[0].value, except it will not throw exceptions if 'person', 'person.items',
		or 'person.items[0]' returns undefined.


		extract( person, 'items', x => x.id==22, 'value' );

		Equivalent to person.items.find(x => x.id==22).value, except it will not throw exceptions if 'person',
		'person.items', or 'person.items[0].find(x => x.id==22)' is undefined.
	*/

	public extract(...args: any[]) {

		if (!args[0]) {
			return undefined;
		}

		let trace = false;

		if (args[0] === '(TRACE)'.toUpperCase()) {
			trace = true;
			args.shift();

			console.log('------------------------------\nEXTRACT TRACE\n------------------------------');
		}

		let obj = args.shift();

		while (args.length > 0) {
			const next = args.shift();

			if (next.constructor === String) {
				if (trace) { console.log('OBJECT PROPERTY LOOKUP'); }
				obj = obj[next];

			} else if (next.constructor === Array) {
				if (trace) { console.log('ARRAY INDEX LOOKUP'); }
				obj = obj[next[0]];

			} else if (next.constructor === Function) {
				if (trace) { console.log('ARRAY SEARCH'); }
				if (obj.constructor !== Array) {
					if (trace) { console.log('NOT AN ARRAY - RETURNING UNDEFINED\n------------------------------'); }
					return undefined;
				}
				obj = obj.find(next);

			} else {
				if (trace) { console.log('ENCOUNTERED INVALID ARGUMENT - RETURNING UNDEFINED\n------------------------------'); }
				return undefined;
			}

			if (obj === undefined) {
				if (trace) { console.log('NOT FOUND - RETURNING UNDEFINED\n------------------------------'); }
				return undefined;
			}
		}

		if (trace) { console.log('EXTRACT WAS SUCCESSFUL\n------------------------------'); }
		return obj;
	}

	/*
		Returns a partially applied version of the util.extract function.
		For example:
			this.util.extract(json, 'a','b','c') will yeild the same result as
			const extract = this.util.partiallyApplyExtract(json,'a','b')
			extract('c')
		this is useful if you want to apply the same initial arguments multiple times.
	*/
	public partiallyApplyExtract(...args) {
		return ((...args2) => {
			const merged = [...args, ...args2];
			return this.extract(...merged);
		});
	}

	/**
	 * Fetch a JS script from a URL, add it to the DOM, and execute it.
	 *
	 * https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file
	 * https://stackoverflow.com/questions/8578617/inject-a-script-tag-with-remote-src-and-wait-for-it-to-execute
	 */
	public loadScript(url: string): Promise<any> {

		return new Promise ((resolve, reject) => {
			if (this.scripts.includes(url)) {
				resolve(true);
			} else {
				const script = this.document.createElement('script');
				script.src = url;
				script.async = true;

				if (script.readyState) {  // IE
					script.onreadystatechange = () => {
						if (script.readyState === 'loaded' || script.readyState === 'complete') {
							script.onreadystatechange = null;
							this.scripts.push(url);
							resolve(true);
						}
					};
				} else {  // Others
					script.onload = () => {
						this.scripts.push(url);
						resolve(true);
					};
				}
				this.document.head.appendChild(script);
			}
		});
	}


	/**
	 * Takes in an array and a predicate, and returns the first array element matching the predicate,
	 * removing it from the array.
	 */
	public pickOneFromArray(array, predicate) {

		const e = array.find(predicate);
		const index = array.indexOf(e);
		if (index !== -1) {
			return array.splice(index, 1)[0];
		} else {
			return undefined;
		}
	}

	public getComponentId(component) {
		let id = this.extract(component, 'Id') || '';
		if (id) {
			// Id is either 'componentID' or 'componentID-templateID'.
			id = `${this.constants.COMPONENT_ID_PREFIX}-${id.split('-')[0]}`
		}

		return id;
	}

	/**
	 * Returns the current date as a string in format YYYYxMMxDD with x as an optional separator.
	 */
	public getCurrentDate(separator: string = ''): string
	{
		let date = new Date();
		let year = date.getFullYear();
		let month = `${date.getMonth() + 1}`;
		if (month.length < 2) {
			month = '0' + month;
		}
		let day =`${date.getDate()}`;
		if (day.length < 2) {
			day = '0' + day;
		}
		return `${year}${separator}${month}${separator}${day}`;
	}
	/* Given a number returns the appropirate format
	1400 would return 1.4 KB
	16700000 would return 16.7 MB
	*/
	formatFilesize(fileSizeInBytes: number): string {
		// Retturn empty in case the input is not valid
		if (!fileSizeInBytes) {
			return '';
		}
		const kb = 1000;
		const mb = 1000000;
		const gb = 1000000000;
		let filesize = '';
		if (fileSizeInBytes / gb > 1) {
			filesize = `(${(fileSizeInBytes / gb).toFixed(1)} GB)`;
		} else if (fileSizeInBytes / mb > 1) {
			filesize = `(${(fileSizeInBytes / mb).toFixed(1)} MB)`;
		} else {
			filesize = `(${(fileSizeInBytes / kb).toFixed(1)} KB)`;
		}
		return filesize;
	}
}

result-matching ""

    No results matching ""