typedash
Version:
modern, type-safe collection of utility functions
56 lines (53 loc) • 1.93 kB
JavaScript
import { n as assert } from "./assert-BMSuascf.js";
import { t as createTypeGuard } from "./createTypeGuard-DTvIg0I0.js";
//#region src/functions/_internal/isMaliciousObjectPath.ts
/**
* Determines whether the given property name is malicious or not (e.g. `__proto__` or `constructor`).
* @param propertyName The property name to check for maliciousness.
* @returns true if the property name is malicious, false otherwise.
* @example
* ```ts
* isMaliciousObjectProperty('constructor'); // returns true
* isMaliciousObjectProperty('nonMaliciousPath'); // returns false
* isMaliciousObjectProperty('__proto__'); // returns true
* ```
*/
const isMaliciousObjectProperty = createTypeGuard(Object.getOwnPropertyNames(Object.getPrototypeOf({})));
//#endregion
//#region src/functions/set/set.ts
/**
* Sets a value at the specified (possibly nested) path in an object.
* @template TObject The type of the object.
* @template Path The type of the path.
* @param object The object to set the value in.
* @param path The path to set the value at.
* @param value The value to set.
* @example
* ```ts
* const object: {
* foo?: {
* bar?: {
* anArray: string[];
* };
* }
* };
*
* set(object, 'foo.bar.anArray[0]', 'value');
* object.foo.bar.anArray[0]; // 'value'
*/
function set(object, path, value) {
const segments = path.match(pathSegmentsRegex);
assert(segments !== null, "Invalid path");
assert(segments.every((segment) => isMaliciousObjectProperty(segment) === false), "Potentially malicious path");
let currentObject = object;
for (let index = 0; index < segments.length - 1; index++) {
const segment = segments[index];
if (segment in currentObject === false) currentObject[segment] = Object.create(null);
currentObject = currentObject[segment];
}
currentObject[segments.at(-1)] = value;
}
const pathSegmentsRegex = /[\w-]+/g;
//#endregion
export { set as t };
//# sourceMappingURL=set-DUE9PB5r.js.map