Skip to content

Commit

Permalink
fix(object): has should return early if nothing to split
Browse files Browse the repository at this point in the history
The `hasProperty` function is useful when using the delmiter to test
deep existence of properties, e.g. `one.two.three`. In the case where
it's a root-level property, performance tests show that returning early
is a performance gain.
  • Loading branch information
darinspivey committed Nov 1, 2024
1 parent 5c5dbaf commit 8b815a0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/object/has-property.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ module.exports = function hasProperty(obj, string = '', sep = '.') {
}

const parts = string.split(sep)

if (parts.length === 1) return Object.prototype.hasOwnProperty.call(obj, string)

let ret = obj
/* eslint-disable-next-line no-unused-vars */
const last = parts.pop()
Expand Down
2 changes: 2 additions & 0 deletions test/unit/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ test('object', async (t) => {
t.throws(() => {
object.has(input, 'l1.l1p2.l3p2', 2)
}, /must be a string/ig)

t.equal(has({one: 1}, 'one'), true, 'returns early if there is no delimiter to split')
}).catch(threw)

t.test('object.get', async (t) => {
Expand Down

0 comments on commit 8b815a0

Please sign in to comment.