@storm-stack/utilities
Version:
This package includes various base utility class and various functions to assist in the development process.
58 lines (57 loc) • 1.43 kB
JavaScript
import { isDeepKey, isNumber, toStringKey } from "@storm-stack/types";
import { toPath } from "./to-path.mjs";
export function getField(object, path, defaultValue) {
if (object === null) {
return defaultValue;
}
switch (typeof path) {
case "string": {
const result = object[path];
if (result === void 0) {
if (isDeepKey(path)) {
return getField(object, toPath(path), defaultValue);
}
return defaultValue;
}
return result;
}
case "number":
case "symbol": {
if (isNumber(path)) {
path = 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;
}