Added advanced search function
Some checks failed
Build / Build NPM Project (push) Failing after 20s
Build / Tag Version (push) Has been skipped
Build / Publish Documentation (push) Has been skipped

This commit is contained in:
Zakary Timson 2024-11-15 16:17:52 -05:00
parent fa66820c76
commit 7b4e17e4c4
3 changed files with 5223 additions and 0 deletions

5184
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@ export * from './misc';
export * from './objects';
export * from './path-events';
export * from './promise-progress';
export * from './search';
export * from './string';
export * from './time';
export * from './types';

38
src/search.ts Normal file
View File

@ -0,0 +1,38 @@
import {dotNotation, JSONAttemptParse} from '@ztimson/utils';
export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) {
if(!rows) return [];
return rows.filter(r => {
// Empty search
const value = transform(r);
if(!search) return true;
// Regex search
if(regex) {
return !!Object.values(value).filter((v: any) => {
try { return RegExp(search, 'gm').test(v.toString()); }
catch { return false; }
}).length
}
// Make sure at least one OR passes
const or = search.split('||').map(p => p.trim()).filter(p => !!p);
return -1 != or.findIndex(p => {
// Make sure all ANDs pass
const and = p.split('&&').map(p => p.trim()).filter(p => !!p);
return and.filter(p => {
// Boolean operator
const prop = /(\w+)\s*(==?|!=|>=|>|<=|<)\s*(\w+)/g.exec(p);
if(prop) {
const a = JSON.stringify(JSONAttemptParse(dotNotation<any>(value, prop[1])));
const operator = prop[2] == '=' ? '==' : prop[2];
const b = JSON.stringify(JSONAttemptParse(prop[3]));
return eval(`${a} ${operator} ${b}`);
}
// Case-sensitive
const v = Object.values(value).join('');
if(/[A-Z]/g.test(search)) return v.includes(p);
// Case-insensitive
return v.toLowerCase().includes(p);
}).length == and.length;
})
});
}