Skip to content

Commit

Permalink
feat(internal): validateObject
Browse files Browse the repository at this point in the history
Signed-off-by: Lexus Drumgold <[email protected]>
  • Loading branch information
unicornware committed Dec 9, 2022
1 parent df42e5c commit 7aae60f
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/internal/__tests__/validate-object.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* @file Unit Tests - validateObject
* @module pathe/internal/tests/unit/validateObject
*/

import ERR_INVALID_ARG_TYPE from '../err-invalid-arg-type'
import testSubject from '../validate-object'

describe('unit:internal/validateObject', () => {
let name: string

beforeEach(() => {
name = 'pathObject'
})

it('should return true if value is an object', () => {
// Arrange
const cases: Parameters<typeof testSubject>[0][] = [
{},
new Date(),
JSON.parse(faker.datatype.json())
]

// Act + Expect
cases.forEach(value => expect(testSubject(value, name)).to.be.true)
})

it('should throw if value is not an object', () => {
// Arrange
const cases: Parameters<typeof testSubject>[0][] = [
faker.datatype.array(),
faker.datatype.bigInt(),
faker.datatype.boolean(),
faker.datatype.boolean(),
faker.datatype.number(),
faker.datatype.string()
]

// Act + Expect
cases.forEach(value => {
let error: ERR_INVALID_ARG_TYPE

try {
testSubject(value, name)
} catch (e: unknown) {
error = e as typeof error
}

expect(error!).to.be.instanceOf(ERR_INVALID_ARG_TYPE)
})
})
})
30 changes: 30 additions & 0 deletions src/internal/validate-object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* @file Internal - validateObject
* @module pathe/internal/validateObject
*/

import ERR_INVALID_ARG_TYPE from './err-invalid-arg-type'

/**
* Checks if `value` is an object.
*
* Throws {@linkcode ERR_INVALID_ARG_TYPE} if `value` is not an object.
*
* **Note**: Array values are not considered objects.
*
* [1]: https://nodejs.org/api/errors.html#err_invalid_arg_type
*
* @param {unknown} value - Possible object value
* @param {string} name - `value` label
* @return {boolean} `true` if `value` is an object
* @throws {ERR_INVALID_ARG_TYPE}
*/
const validateObject = (value: unknown, name: string): boolean => {
if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
return true
}

throw new ERR_INVALID_ARG_TYPE(name, 'object', value)
}

export default validateObject

0 comments on commit 7aae60f

Please sign in to comment.