Skip to content

Commit

Permalink
added: object.filter
Browse files Browse the repository at this point in the history
  • Loading branch information
GianlucaGuarini committed Jun 14, 2024
1 parent d332ebd commit f393c93
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
18 changes: 17 additions & 1 deletion objects.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isObject } from './checks.js'

/**
* Helper function to set an immutable property
* @param {Object} source - object where the new property will be set
Expand Down Expand Up @@ -55,5 +57,19 @@ export function defineDefaults(source, defaults) {
* @returns {*} the object we wanted to clone
*/
export function cloneDeep(source) {
return JSON.parse(JSON.stringify(source))
return structuredClone(source)
}

/**
* Like Array.prototype.filter but for objects
* @param {Object} source - target object
* @param {Funciton} filter - filter function
* @return {Object} filtered source or the original source received
*/
export function filter(source, filter) {
return isObject(source)
? Object.fromEntries(
Object.entries(source).filter(([key, value]) => filter(key, value)),
)
: source
}
13 changes: 13 additions & 0 deletions objects.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
defineDefaults,
defineProperties,
defineProperty,
filter,
} from './objects.js'
import { expect } from 'chai'

Expand Down Expand Up @@ -51,4 +52,16 @@ describe('Objects', function () {
expect(clone.surname).to.be.not.ok
expect(clone.name).to.be.equal('hello')
})

it('filter', () => {
const source = { name: 'hello', class: 'test' }
const filtered = filter(source, (key) => key === 'name')

expect(filtered.class).to.be.not.ok
expect(filtered.name).to.be.equal('hello')
})

it('filter (null)', () => {
expect(() => filter(null, (key) => key === 'name')).to.not.throw()
})
})

0 comments on commit f393c93

Please sign in to comment.