UNPKG

1.69 kBJavaScriptView Raw
1import { errorTransform } from '../../transform/utils/errorTransform.js';
2import { setSafeProperty } from '../../../utils/customs.js';
3export function assignFactory(_ref) {
4 var {
5 subset,
6 matrix
7 } = _ref;
8
9 /**
10 * Replace part of an object:
11 *
12 * - Assign a property to an object
13 * - Replace a part of a string
14 * - Replace a matrix subset
15 *
16 * @param {Object | Array | Matrix | string} object
17 * @param {Index} index
18 * @param {*} value
19 * @return {Object | Array | Matrix | string} Returns the original object
20 * except in case of a string
21 */
22 // TODO: change assign to return the value instead of the object
23 return function assign(object, index, value) {
24 try {
25 if (Array.isArray(object)) {
26 // we use matrix.subset here instead of the function subset because we must not clone the contents
27 return matrix(object).subset(index, value).valueOf();
28 } else if (object && typeof object.subset === 'function') {
29 // Matrix
30 return object.subset(index, value);
31 } else if (typeof object === 'string') {
32 // TODO: move setStringSubset into a separate util file, use that
33 return subset(object, index, value);
34 } else if (typeof object === 'object') {
35 if (!index.isObjectProperty()) {
36 throw TypeError('Cannot apply a numeric index as object property');
37 }
38
39 setSafeProperty(object, index.getObjectProperty(), value);
40 return object;
41 } else {
42 throw new TypeError('Cannot apply index: unsupported type of object');
43 }
44 } catch (err) {
45 throw errorTransform(err);
46 }
47 };
48}
\No newline at end of file