diff options
author | elioat <elioat@tilde.institute> | 2024-12-24 08:56:21 -0500 |
---|---|---|
committer | elioat <elioat@tilde.institute> | 2024-12-24 08:56:21 -0500 |
commit | f717dbccbfbfbd64f352440dcdc42cce72936b70 (patch) | |
tree | 075c4b6372387fccd0217d068cec30a4d98a557e /js/where/where.js | |
parent | dd37de88a2e87cabd2f5a60369e3c38558f32ebc (diff) | |
download | tour-f717dbccbfbfbd64f352440dcdc42cce72936b70.tar.gz |
*
Diffstat (limited to 'js/where/where.js')
-rw-r--r-- | js/where/where.js | 41 |
1 files changed, 2 insertions, 39 deletions
diff --git a/js/where/where.js b/js/where/where.js index cef80f3..60e3797 100644 --- a/js/where/where.js +++ b/js/where/where.js @@ -5,19 +5,17 @@ * @returns {Array} - Filtered array of objects */ const where = (collection, properties) => { - // null/undefined inputs + if (!collection || !properties) { return []; } - // Cache property paths and their split versions for performance const propertyPaths = Object.entries(properties).map(([key, value]) => ({ path: key, parts: key.split('.'), value })); - // An optimized nested value getter with memoization const getNestedValue = (() => { const cache = new WeakMap(); @@ -45,20 +43,17 @@ const where = (collection, properties) => { }; })(); - // An optimized equality comparison const isEqual = (value1, value2) => { - // Handle null/undefined cases first for faster returns + if (value2 === undefined) return true; if (value1 === value2) return true; if (value1 === null || value2 === null) return false; - // Array comparison if (Array.isArray(value1) && Array.isArray(value2)) { return value1.length === value2.length && value1.every((val, idx) => isEqual(val, value2[idx])); } - // Object comparison if (typeof value2 === 'object') { return Object.entries(value2).every(([key, val]) => value1 && isEqual(value1[key], val) @@ -68,13 +63,11 @@ const where = (collection, properties) => { return false; }; - // Property matcher const matchesProperties = item => propertyPaths.every(({ parts, value }) => isEqual(getNestedValue(item, parts), value) ); - // Input validation if (!Array.isArray(collection) || typeof properties !== 'object') { return []; } @@ -82,37 +75,7 @@ const where = (collection, properties) => { return collection.filter(matchesProperties); }; -// Example usage with nested structures: -/* -const data = [ - { - name: 'John', - age: 30, - preferences: { - theme: 'dark', - notifications: { email: true, sms: false } - } - }, - { - name: 'Jane', - age: 25, - preferences: { - theme: 'light', - notifications: { email: false, sms: true } - } - } -]; - -// Find users with specific preferences -const darkThemeUsers = where(data, { - preferences: { theme: 'dark' } -}); -// Find users with specific notification settings -const emailSubscribers = where(data, { - preferences: { notifications: { email: true } } -}); -*/ if (typeof module !== 'undefined' && module.exports) { module.exports = where; |