The tricky part wasn't the filtering logic itself, that's just a reduce or every call.
Start by clarifying the requirements: the filter should accept multiple conditions, each on a single field, and return objects that satisfy all (AND logic). Then propose a type-safe representation, such as a discriminated union of condition objects keyed by field name, and a generic filter function that infers the object type and validates conditions at compile time. Discuss scalability by allowing easy addition of new fields and operators without modifying the core filter logic.
Pro tip: Mention that you'd use TypeScript's mapped types and conditional types to ensure each condition's value type matches the field's type, preventing runtime errors. Also, highlight that you'd design for extensibility by separating condition definition from evaluation, perhaps using a registry pattern.
Ask if conditions are always ANDed, if OR/NOT logic is needed, and what operators (equality, range, etc.) must be supported. Confirm the data shape and whether fields are optional.
Propose a discriminated union where each condition specifies a field (keyof T) and an operator, with the value type tied to the field's type using generics. For example: type Condition<T> = { [K in keyof T]: { field: K; operator: Operator; value: T[K] } }[keyof T].
Write a generic function: function filter<T>(items: T[], conditions: Condition<T>[]): T[]. Ensure it returns the same type T and that conditions are validated at compile time.
For each item, check all conditions using a switch on operator or a lookup map. Ensure short-circuit evaluation for performance. Keep the logic pure and testable.
Explain how to add new fields or operators without changing the filter function (e.g., via a condition evaluator registry). Mention potential performance concerns with many conditions and how to optimize (e.g., indexing, early exit).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.