/
githubmirror
/
immutable-js
Обзор
Документация
Войти
/
githubmirror
/
immutable-js
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
v5.1.2
src/functional/set.ts
76 строк
2 KB
Julien Deniau
Migrate functional files to TS (#2063)
23 мар 2025, 00:38
Не верифицирован
23 мар 2025, 00:38
70826e6
Код
Авторство
О чём код?
import type { Collection, Record } from '../../type-definitions/immutable'; import { isImmutable } from '../predicates/isImmutable'; import hasOwnProperty from '../utils/hasOwnProperty'; import isDataStructure from '../utils/isDataStructure'; import shallowCopy from '../utils/shallowCopy'; /** * Returns a copy of the collection with the value at key set to the provided * value. * * A functional alternative to `collection.set(key, value)` which will also * work with plain Objects and Arrays as an alternative for * `collectionCopy[key] = value`. * * <!-- runkit:activate --> * ```js * import { set } from 'immutable'; * * const originalArray = [ 'dog', 'frog', 'cat' ] * set(originalArray, 1, 'cow') // [ 'dog', 'cow', 'cat' ] * console.log(originalArray) // [ 'dog', 'frog', 'cat' ] * const originalObject = { x: 123, y: 456 } * set(originalObject, 'x', 789) // { x: 789, y: 456 } * console.log(originalObject) // { x: 123, y: 456 } * ``` */ export function set<K, V, C extends Collection<K, V>>( collection: C, key: K, value: V ): C; export function set< TProps extends object, C extends Record<TProps>, K extends keyof TProps, >(record: C, key: K, value: TProps[K]): C; export function set<V, C extends Array<V>>( collection: C, key: number, value: V ): C; export function set<C, K extends keyof C>(object: C, key: K, value: C[K]): C; export function set<V, C extends { [key: string]: V }>( collection: C, key: string, value: V ): C; export function set<K, V, C extends Collection<K, V> | { [key: string]: V }>( collection: C, key: K | string, value: V ): C { if (!isDataStructure(collection)) { throw new TypeError( 'Cannot update non-data-structure value: ' + collection ); } if (isImmutable(collection)) { // @ts-expect-error weird "set" here, if (!collection.set) { throw new TypeError( 'Cannot update immutable value without .set() method: ' + collection ); } // @ts-expect-error weird "set" here, return collection.set(key, value); } // @ts-expect-error mix of key and string here. Probably need a more fine type here if (hasOwnProperty.call(collection, key) && value === collection[key]) { return collection; } const collectionCopy = shallowCopy(collection); // @ts-expect-error mix of key and string here. Probably need a more fine type here collectionCopy[key] = value; return collectionCopy; }