UNPKG

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