Skip to content

Commit f393c93

Browse files
added: object.filter
1 parent d332ebd commit f393c93

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

objects.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isObject } from './checks.js'
2+
13
/**
24
* Helper function to set an immutable property
35
* @param {Object} source - object where the new property will be set
@@ -55,5 +57,19 @@ export function defineDefaults(source, defaults) {
5557
* @returns {*} the object we wanted to clone
5658
*/
5759
export function cloneDeep(source) {
58-
return JSON.parse(JSON.stringify(source))
60+
return structuredClone(source)
61+
}
62+
63+
/**
64+
* Like Array.prototype.filter but for objects
65+
* @param {Object} source - target object
66+
* @param {Funciton} filter - filter function
67+
* @return {Object} filtered source or the original source received
68+
*/
69+
export function filter(source, filter) {
70+
return isObject(source)
71+
? Object.fromEntries(
72+
Object.entries(source).filter(([key, value]) => filter(key, value)),
73+
)
74+
: source
5975
}

objects.spec.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
defineDefaults,
44
defineProperties,
55
defineProperty,
6+
filter,
67
} from './objects.js'
78
import { expect } from 'chai'
89

@@ -51,4 +52,16 @@ describe('Objects', function () {
5152
expect(clone.surname).to.be.not.ok
5253
expect(clone.name).to.be.equal('hello')
5354
})
55+
56+
it('filter', () => {
57+
const source = { name: 'hello', class: 'test' }
58+
const filtered = filter(source, (key) => key === 'name')
59+
60+
expect(filtered.class).to.be.not.ok
61+
expect(filtered.name).to.be.equal('hello')
62+
})
63+
64+
it('filter (null)', () => {
65+
expect(() => filter(null, (key) => key === 'name')).to.not.throw()
66+
})
5467
})

0 commit comments

Comments
 (0)