openaire-library/utils/HelperFunctions.class.ts

77 lines
1.8 KiB
TypeScript

export class HelperFunctions {
public static scroll() {
HelperFunctions.scrollTo(0,0);
}
public static scrollTo(x,y) {
if (typeof document !== 'undefined') {
window.scrollTo(x,y);
}
}
public static scrollToId(elementId:string) {
if (typeof document !== 'undefined' && document.getElementById(elementId)) {
document.getElementById(elementId).scrollIntoView();
}
}
public static isTiny(url: string) {
return (url.indexOf('tinyurl.com') !== -1);
}
public static copy(obj: any): any {
let copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (let i = 0, len = obj.length; i < len; i++) {
copy[i] = HelperFunctions.copy(obj[i]);
}
return copy;
}
// Handle Map
if (obj instanceof Map) {
return new Map(obj.entries());
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (let attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = HelperFunctions.copy(obj[attr]);
}
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
public static equals(object1, object2) {
return object1 === object2 || JSON.stringify(object1) === JSON.stringify(object2);
}
public static encodeArray(elements: string[]): string[] {
let encoded: string[] = [];
elements.forEach(element => {
encoded.push(encodeURIComponent(element));
});
return encoded;
}
public static getValues(value: any): any[] {
return Object.keys(value).map(key => value[key]);
}
}