Recursive search

PHOTO EMBED

Wed Sep 20 2023 09:14:47 GMT+0000 (Coordinated Universal Time)

Saved by @mangouste #typescript

import { isArray as isArrayUtils, isObject as isObjectUtils } from '@utils/functions';

import { compareString } from '../compareString';

// ****************************
// ? move to @utils/functions
type MyObject = { [key: string]: unknown };
type IsObject = (data: unknown) => data is MyObject;
export const isObject: IsObject = (data): data is MyObject => isObjectUtils(data);

type Array = unknown[];
type IsArray = (data: unknown) => data is Array;
export const isArray: IsArray = (data): data is Array => isArrayUtils(data);
// ****************************

export type FilterFileByValue = (file: unknown, value: string) => boolean;

export const filterFileByValue: FilterFileByValue = (file, value) => {
	try {
		const fileValues = (isObject(file) && Object.values(file)) || [];
		
		const filteredFileValues = fileValues.filter((fileValue) => {
			if (typeof fileValue === 'string') {
				return compareString({ string1: fileValue, string2: value });
			}

			if (isArray(fileValue)) {
				const values = fileValue.filter((nestedFile) => filterFileByValue(nestedFile, value));
				return !!values.length;
			
			}
		
		return filterFileByValue(fileValue, value);
		
		});
		return !!filteredFileValues.length;
		
	} catch {
		return false;
	}

};
content_copyCOPY