@enonic/js-utils
Version:
Enonic XP JavaScript Utils
84 lines (73 loc) • 2.37 kB
JavaScript
// value/isObject.ts
var isObject = (value) => Object.prototype.toString.call(value).slice(8, -1) === "Object";
// value/isBasicObject.ts
var isBasicObject = (value) => typeof value === "object";
// value/isNumber.ts
function isNumber(value) {
return typeof value === "number" && isFinite(value);
}
// value/isStringLiteral.ts
var isStringLiteral = (value) => typeof value === "string";
// value/isStringObject.ts
var isStringObject = (value) => value instanceof String;
// value/isString.ts
var isString = (value) => isStringLiteral(value) || isStringObject(value);
// value/isSymbol.ts
var isSymbol = (value) => typeof value === "symbol";
// value/isPropertyKey.ts
var isPropertyKey = (value) => isString(value) || isNumber(value) || isSymbol(value);
// value/toStr.ts
function toStr(value, replacer, space = 4) {
return JSON.stringify(value, replacer, space);
}
// object/hasOwnProperty.ts
function hasOwnProperty(obj, propKey) {
if (!isBasicObject(obj)) {
throw new Error(`First parameter to hasOwnProperty must be a basic Object! ${toStr(obj)}`);
}
if (!isPropertyKey(propKey)) {
throw new Error(`Second parameter to hasOwnProperty must be a PropertyKey (string|number|symbol)! ${toStr(propKey)}`);
}
return obj.hasOwnProperty(propKey);
}
// object/setIn.ts
function isUnsafeKey(key) {
return key === "__proto__" || key === "constructor" || key === "prototype";
}
function setIn(target, path, value) {
if (!path || !isObject(target)) return target;
if (!Array.isArray(path)) {
path = path.split(".");
}
let leafKey = path[0];
if (isUnsafeKey(leafKey)) {
throw new Error(`setIn: unsafe root key: "${String(leafKey)}"`);
}
let obj = target;
if (path.length > 1) {
const pathLength = path.length;
leafKey = path[pathLength - 1];
if (isUnsafeKey(leafKey)) {
throw new Error(`setIn: unsafe leaf key: "${String(leafKey)}"`);
}
for (let i = 0; i < pathLength - 1; i++) {
const branchKey = path[i];
if (isUnsafeKey(branchKey)) {
throw new Error(`setIn: unsafe branch key: "${String(branchKey)}"`);
}
if (!hasOwnProperty(obj, branchKey)) {
obj[branchKey] = {};
}
obj = obj[branchKey];
}
}
if (typeof value !== "undefined") {
obj[leafKey] = value;
} else {
delete obj[leafKey];
}
return target;
}
export {
setIn
};