fuse-angular/src/@fuse/utils/index.ts

160 lines
3.5 KiB
TypeScript
Raw Normal View History

export class FuseUtils
{
2018-05-20 07:12:31 +00:00
/**
* Filter array by string
*
* @param mainArr
* @param searchText
* @returns {any}
*/
public static filterArrayByString(mainArr, searchText): any
{
2017-07-28 09:26:56 +00:00
if ( searchText === '' )
{
return mainArr;
}
searchText = searchText.toLowerCase();
return mainArr.filter(itemObj => {
return this.searchInObj(itemObj, searchText);
});
}
2018-05-20 07:12:31 +00:00
/**
* Search in object
*
* @param itemObj
* @param searchText
* @returns {boolean}
*/
public static searchInObj(itemObj, searchText): boolean
{
for ( const prop in itemObj )
{
if ( !itemObj.hasOwnProperty(prop) )
{
continue;
}
const value = itemObj[prop];
if ( typeof value === 'string' )
{
2017-09-18 07:47:35 +00:00
if ( this.searchInString(value, searchText) )
{
return true;
}
}
else if ( Array.isArray(value) )
{
if ( this.searchInArray(value, searchText) )
{
return true;
}
}
if ( typeof value === 'object' )
{
if ( this.searchInObj(value, searchText) )
{
return true;
}
}
}
}
2018-05-20 07:12:31 +00:00
/**
* Search in array
*
* @param arr
* @param searchText
* @returns {boolean}
*/
public static searchInArray(arr, searchText): boolean
{
for ( const value of arr )
{
if ( typeof value === 'string' )
{
2017-09-18 07:47:35 +00:00
if ( this.searchInString(value, searchText) )
{
return true;
}
}
if ( typeof value === 'object' )
{
if ( this.searchInObj(value, searchText) )
{
return true;
}
}
}
}
2018-05-20 07:12:31 +00:00
/**
* Search in string
*
* @param value
* @param searchText
* @returns {any}
*/
public static searchInString(value, searchText): any
{
2017-08-17 07:31:04 +00:00
return value.toLowerCase().includes(searchText);
}
2017-07-28 14:40:11 +00:00
2018-05-20 07:12:31 +00:00
/**
* Generate a unique GUID
*
* @returns {string}
*/
public static generateGUID(): string
2017-07-28 14:40:11 +00:00
{
2018-05-20 07:12:31 +00:00
function S4(): string
2017-07-28 14:40:11 +00:00
{
2017-11-01 11:32:25 +00:00
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
2017-07-28 14:40:11 +00:00
}
2017-11-01 11:32:25 +00:00
return S4() + S4();
2017-07-28 14:40:11 +00:00
}
2018-05-20 07:12:31 +00:00
/**
* Toggle in array
*
* @param item
* @param array
*/
public static toggleInArray(item, array): void
{
if ( array.indexOf(item) === -1 )
{
array.push(item);
}
else
{
array.splice(array.indexOf(item), 1);
}
}
2017-11-01 11:32:25 +00:00
2018-05-20 07:12:31 +00:00
/**
* Handleize
*
* @param text
* @returns {string}
*/
public static handleize(text): string
2017-11-01 11:32:25 +00:00
{
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
}