import {Indexable} from '../interfaces/indexable'; /** * Helper to get and set Attributes on Objects */ export class ObjectHelper { /** * Checking if the Element is an Object * @param {any} obj * @return {boolean} */ static isObject(obj: any): boolean { return obj != null && typeof (obj) === 'object'; } /** * Formatting date as German * @param {string} date yyyy-mm-dd * @return {string} dd.mm.yyyy */ static formatDate(date: string | undefined): string { if (date) { return `${date.substr(8, 2)}.${date.substr(5, 2)}.${date.substr(0, 4)}`; } else { return ''; } } /** * Adding Days to Date * @param {Date} date * @param {number} days * @return {Date} */ static addDaysToDate(date: Date, days: number): Date { const result = new Date(date); result.setDate(result.getDate() + days); return result; } /** * Converts a date to a string * @param {Date} date * @return {string} */ static dateToString(date: Date): string { const d = new Date(date); let month = '' + (d.getMonth() + 1); let day = '' + d.getDate(); const year = d.getFullYear(); if (month.length < 2) { month = '0' + month; } if (day.length < 2) { day = '0' + day; } return [year, month, day].join('-'); } /** * Getting Value from JSON-Object * @param {Indexable} object * @param {string} key * @return {any} */ static get(object: Indexable, key: string): any { try { const attributes: string[] = key.split('.'); return this._iterateThrough(object, attributes); } catch (ex) { return undefined; } } /** * Iterating Through Object * @param {Indexable} obj * @param {string[]} attributes * @param {number} depth * @return {any} * @private */ static _iterateThrough(obj: Indexable, attributes: string[], depth = 0): any { if (depth < 0) return undefined; while (attributes.length > depth) { const attribute: string = attributes.shift() as string; if (!obj) throw new Error('Unknown Key'); if (attribute.includes('[')) { const index = attribute.indexOf('['); const a = attribute.substr(0, index); const matchB = attribute.match(/\d+/); obj = obj[a][matchB ? matchB[0] : 0]; } else { obj = obj[attribute]; } } return obj; } /** * Setting value for Object * @param {Indexable} object * @param {string} key * @param {any} value */ static set(object: Indexable, key: string, value: any): void { const attributes: string[] = key.split('.'); object = this._iterateThrough(object, attributes, 1); const property = attributes[0]; object[property] = value; } /** * Converts a string to bool * @param {string} v * @return {boolean} */ static stringToBool(v: string): boolean { return v === 'true'; } /** * Object to String * @param {Object} obj * @return {string} */ static objectToStringDeep(obj: any): string { if (!obj) return ''; return Object.keys(obj).map((k: string) => { const value: any = obj[k]; if (typeof (value) == 'object') { return ObjectHelper.objectToStringDeep(value); } else { return value; } }).toString(); } }