From ad25a69ebc86efe58ca37289b5892ac35dff82e9 Mon Sep 17 00:00:00 2001 From: Craig Weber Date: Tue, 23 Jul 2024 15:28:13 -0400 Subject: [PATCH] feat: Add isSet type guard (#31) --- src/index.ts | 1 + src/utils/is-set.ts | 8 ++++++++ tests/utils/is-set.test.ts | 28 ++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 src/utils/is-set.ts create mode 100644 tests/utils/is-set.test.ts diff --git a/src/index.ts b/src/index.ts index a5f78d9..48129d5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,6 +22,7 @@ export * from './utils/is-number'; export * from './utils/is-object'; export * from './utils/is-promise'; export * from './utils/is-promise-like'; +export * from './utils/is-set'; export * from './utils/is-string'; export * from './utils/is-undefined'; export * from './utils/is-null'; diff --git a/src/utils/is-set.ts b/src/utils/is-set.ts new file mode 100644 index 0000000..98ab264 --- /dev/null +++ b/src/utils/is-set.ts @@ -0,0 +1,8 @@ +/** + * Type guard for `Set`s. + * + * @returns `true` if `o` is a `Set`, regardless of the types that it contains + */ +export function isSet(o: unknown): o is Set { + return o instanceof Set; +} diff --git a/tests/utils/is-set.test.ts b/tests/utils/is-set.test.ts new file mode 100644 index 0000000..6166b71 --- /dev/null +++ b/tests/utils/is-set.test.ts @@ -0,0 +1,28 @@ +import { expect } from 'chai'; +import * as t from '../../src/index'; + + +describe('isSet', () => { + + it('correctly classifies sets', () => { + expect(t.isSet(new Set([]))).to.strictlyEqual(true); + expect(t.isSet(new Set([ 'a', 'b', 'c' ]))).to.strictlyEqual(true); + expect(t.isSet(new Set([ 4 ]))).to.strictlyEqual(true); + expect(t.isSet(new Set([ 'a', 'b', 'c', 4 ]))).to.strictlyEqual(true); + expect(t.isSet(new Set())).to.strictlyEqual(true); + }); + + it('correctly classifies non-sets', () => { + expect(t.isSet([])).to.strictlyEqual(false); + expect(t.isSet({})).to.strictlyEqual(false); + expect(t.isSet(4)).to.strictlyEqual(false); + expect(t.isSet('')).to.strictlyEqual(false); + expect(t.isSet('a')).to.strictlyEqual(false); + expect(t.isSet(true)).to.strictlyEqual(false); + expect(t.isSet(undefined)).to.strictlyEqual(false); + expect(t.isSet(null)).to.strictlyEqual(false); + expect(t.isSet({ length: 0 })).to.strictlyEqual(false); + expect(t.isSet(() => {})).to.strictlyEqual(false); + }); + +});