Skip to content

Commit

Permalink
feat: add isWeakMap function (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 9, 2024
1 parent aacd5be commit f32cfd5
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 0 deletions.
9 changes: 9 additions & 0 deletions benchmarks/typed/isWeakMap.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as _ from 'radashi'
import { bench } from 'vitest'

describe('isWeakMap', () => {
bench('with no arguments', () => {
_.isWeakMap()
})
})

16 changes: 16 additions & 0 deletions docs/typed/isWeakMap.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
title: isWeakMap
description: Returns true for WeakMap instances
---

## Basic usage

Returns true for `WeakMap` instances, even if they are subclass instances or from
other [realms](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms).

```ts
import * as _ from 'radashi'

_.isWeakMap(new WeakMap()) // true
_.isWeakMap(new (class extends WeakMap {})()) // true
```
1 change: 1 addition & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export * from './typed/isSet.ts'
export * from './typed/isString.ts'
export * from './typed/isSymbol.ts'
export * from './typed/isTagged.ts'
export * from './typed/isWeakMap.ts'
export * from './typed/isWeakSet.ts'

export * from './types'
7 changes: 7 additions & 0 deletions src/typed/isWeakMap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { isTagged } from 'radashi'

export function isWeakMap<K extends WeakKey = WeakKey, V = unknown>(
value: unknown,
): value is WeakMap<K, V> {
return isTagged(value, '[object WeakMap]')
}
23 changes: 23 additions & 0 deletions tests/typed/isWeakMap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as vm from 'node:vm'
import * as _ from 'radashi'

describe('isWeakMap', () => {
test('returns true for WeakMap instances', () => {
expect(_.isWeakMap(new WeakMap())).toBe(true)
})
test('returns true for WeakMap subclass instances', () => {
expect(_.isWeakMap(new (class extends WeakMap {})())).toBe(true)
})
test('returns true for WeakMap instances from other realms', () => {
expect(_.isWeakMap(vm.runInNewContext('new WeakMap()'))).toBe(true)
})
test('returns false for undefined', () => {
expect(_.isWeakMap(undefined)).toBe(false)
})
test('returns false for null', () => {
expect(_.isWeakMap(null)).toBe(false)
})
test('returns false for non-WeakMap objects', () => {
expect(_.isWeakMap({})).toBe(false)
})
})

0 comments on commit f32cfd5

Please sign in to comment.