How to Build a Custom Filter: Step-by-Step Guide
Goal
Build a reusable custom filter (e.g., for data processing or UI lists) that accepts input, applies transformation or criteria, and returns filtered output.
Assumptions
- Target environment: JavaScript (Node/browser) using functional style.
- Input: array of objects.
- Filter: configurable predicate and optional transform.
1. Define the filter interface
- Input: array
- Predicate: function(item, index) → boolean
- Transform (optional): function(item) → item’
- Options: includeOriginal (boolean), limit (number)
2. Implementation (JavaScript)
javascript
// createCustomFilter returns a function that filters arrays per config function createCustomFilter({ predicate, transform, includeOriginal = false, limit = Infinity }) { if (typeof predicate !== ‘function’) throw new Error(‘predicate must be a function’); return function (arr) { const out = []; for (let i = 0; i < arr.length && out.length < limit; i++) { const item = arr[i]; if (predicate(item, i, arr)) { out.push(transform ? transform(item, i, arr) : (includeOriginal ? item : { …item })); } } return out; }; }
3. Example usage
javascript
const users = [ { id:1, name:‘Ana’, role:‘admin’, lastActive: ‘2026-01-30’ }, { id:2, name:‘Ben’, role:‘user’, lastActive: ‘2025-12-10’ }, { id:3, name:‘Cara’, role:‘user’, lastActive: ‘2026-02-01’ } ]; const recentActiveUsers = createCustomFilter({ predicate: u => new Date(u.lastActive) > new Date(‘2026-01-01’), transform: u => ({ id: u.id, name: u.name }), limit: 10 }); console.log(recentActiveUsers(users)); // -> [{ id:1, name:‘Ana’ }, { id:3, name:‘Cara’ }]
4. Testing
- Unit test predicates with edge cases (nulls, missing fields).
- Test transform side effects (pure vs impure).
- Performance: measure for large arrays; consider streaming or indexes.
5. Enhancements
- Support async predicates/transforms (Promise).
- Add composable filters (and/or/not).
- Provide config schema validation.
- Expose metrics (count examined, matched).
6. Security & correctness
- Sanitize inputs if predicates evaluate user-supplied code.
- Avoid mutating original data unless explicitly requested.
7. Quick checklist before production
- Validate config types.
- Add tests for typical and edge cases.
- Handle async if needed.
- Document API and examples.
Leave a Reply