@storm-stack/utilities
Version:
This package includes various base utility class and various functions to assist in the development process.
66 lines (65 loc) • 1.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getField = getField;
var _types = require("@storm-stack/types");
var _toPath = require("./to-path.cjs");
function getField(object, path, defaultValue) {
if (object === null) {
return defaultValue;
}
switch (typeof path) {
case "string":
{
const result = object[path];
if (result === void 0) {
if ((0, _types.isDeepKey)(path)) {
return getField(object, (0, _toPath.toPath)(path), defaultValue);
}
return defaultValue;
}
return result;
}
case "number":
case "symbol":
{
if ((0, _types.isNumber)(path)) {
path = (0, _types.toStringKey)(path);
}
const result = Array.isArray(path) ? void 0 : object[path];
if (result === void 0) {
return defaultValue;
}
return result;
}
default:
{
if (Array.isArray(path)) {
return getWithPath(object, path, defaultValue);
}
path = Object.is(path?.valueOf(), -0) ? "-0" : String(path);
const result = object[path];
if (result === void 0) {
return defaultValue;
}
return result;
}
}
}
function getWithPath(object, path, defaultValue) {
if (path.length === 0) {
return defaultValue;
}
let current = object;
for (const element_ of path) {
if (current === null) {
return defaultValue;
}
current = current[element_];
}
if (current === void 0) {
return defaultValue;
}
return current;
}