I have created a custom pipe to filter values within an array of objects. While the basic functionality is in place, I am encountering difficulties when handling empty strings, nulls, and undefined values. When any of these values are passed to the pipe, the expected behavior is for all values from the array to be returned. The pipe is designed to filter based on an object's property, as well as filtering against an array of primitive string or numeric values. I have written several test cases, most of which are passing successfully except for those related to specific scenarios mentioned in this post.
custom-filter.pipe.ts
export class CustomFilterPipe implements PipeTransform {
transform(data: any[], arguments: any[] | any): any[] {
const propToFilter = arguments[1]; // property to filter on
const userInput = arguments[0] || arguments; // user input for filtering
return data.filter((item: any) => {
if (item[propToFilter] && userInput !== ('' || undefined || null))
return item[propToFilter].toString().includes(userInput);
else if (userInput === ('' || undefined || null)) // addressing the "empty" cases
return (item[propToFilter].toString().includes(item) || item.toString().includes(item));
else return item.toString().includes(userInput);
});
}
}
failing test case
it('should return a list of all matches if no user input is provided', function () {
const items = [
{value: 'apple'},
{value: 'banana'},
{value: 'cherry'},
{value: 'date'}
];
const filterProp = 'value';
const numbers = [10, 20, 30];
let output = pipe.transform(items, ['', filterProp]);
expect(output).toEqual(items);
output = pipe.transform(items, [null, filterProp]);
expect(output).toEqual(items);
output = pipe.transform(items, [undefined, filterProp]);
expect(output).toEqual(items);
output = pipe.transform(numbers, '');
expect(output).toEqual([10, 20, 30]);
output = pipe.transform(numbers, null);
expect(output).toEqual([10, 20, 30]);
output = pipe.transform(numbers, undefined);
expect(output).toEqual([10, 20, 30]);
});
The expect
statement in the failing test case is currently returning an empty array instead of the expected full list of values (i.e. items
or numbers
).