openaire-library/utils/HelperFunctions.class.ts

61 lines
1.3 KiB
TypeScript

export class HelperFunctions {
public static scroll() {
if (typeof document !== 'undefined') {
window.scrollTo(0, 0);
}
}
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 encodeArray(elements: string[]): string[] {
let encoded: string[] = [];
elements.forEach(element => {
encoded.push(encodeURIComponent(element));
});
return encoded;
}
}