|
| 1 | +import type { Collection, Record } from '../../type-definitions/immutable'; |
| 2 | +import { isImmutable } from '../predicates/isImmutable'; |
| 3 | +import { has } from './has'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Returns the value within the provided collection associated with the |
| 7 | + * provided key, or notSetValue if the key is not defined in the collection. |
| 8 | + * |
| 9 | + * A functional alternative to `collection.get(key)` which will also work on |
| 10 | + * plain Objects and Arrays as an alternative for `collection[key]`. |
| 11 | + * |
| 12 | + * <!-- runkit:activate --> |
| 13 | + * ```js |
| 14 | + * const { get } = require('immutable') |
| 15 | + * get([ 'dog', 'frog', 'cat' ], 1) // 'frog' |
| 16 | + * get({ x: 123, y: 456 }, 'x') // 123 |
| 17 | + * get({ x: 123, y: 456 }, 'z', 'ifNotSet') // 'ifNotSet' |
| 18 | + * ``` |
| 19 | + */ |
| 20 | +export function get<K, V>(collection: Collection<K, V>, key: K): V | undefined; |
| 21 | +export function get<K, V, NSV>( |
| 22 | + collection: Collection<K, V>, |
| 23 | + key: K, |
| 24 | + notSetValue: NSV |
| 25 | +): V | NSV; |
| 26 | +export function get<TProps extends object, K extends keyof TProps>( |
| 27 | + record: Record<TProps>, |
| 28 | + key: K, |
| 29 | + notSetValue: unknown |
| 30 | +): TProps[K]; |
| 31 | +export function get<V>(collection: Array<V>, key: number): V | undefined; |
| 32 | +export function get<V, NSV>( |
| 33 | + collection: Array<V>, |
| 34 | + key: number, |
| 35 | + notSetValue: NSV |
| 36 | +): V | NSV; |
| 37 | +export function get<C extends object, K extends keyof C>( |
| 38 | + object: C, |
| 39 | + key: K, |
| 40 | + notSetValue: unknown |
| 41 | +): C[K]; |
| 42 | +export function get<V>( |
| 43 | + collection: { [key: string]: V }, |
| 44 | + key: string |
| 45 | +): V | undefined; |
| 46 | +export function get<V, NSV>( |
| 47 | + collection: { [key: string]: V }, |
| 48 | + key: string, |
| 49 | + notSetValue: NSV |
| 50 | +): V | NSV; |
| 51 | +export function get<K extends PropertyKey, V, NSV>( |
| 52 | + collection: Collection<K, V> | Array<V> | { [key: string]: V }, |
| 53 | + key: K, |
| 54 | + notSetValue?: NSV |
| 55 | +): V | NSV { |
| 56 | + return isImmutable(collection) |
| 57 | + ? collection.get(key, notSetValue) |
| 58 | + : !has(collection, key) |
| 59 | + ? notSetValue |
| 60 | + : // @ts-expect-error weird "get" here, |
| 61 | + typeof collection.get === 'function' |
| 62 | + ? // @ts-expect-error weird "get" here, |
| 63 | + collection.get(key) |
| 64 | + : // @ts-expect-error key is unknown here, |
| 65 | + collection[key]; |
| 66 | +} |
0 commit comments