@lodestar/utils
Version:
Utilities required across multiple lodestar packages
75 lines • 2.57 kB
JavaScript
import Case from "case";
export function toExpectedCase(value, expectedCase = "camel", customCasingMap) {
if (expectedCase === "notransform")
return value;
if (customCasingMap?.[value])
return customCasingMap[value];
switch (expectedCase) {
case "param":
return Case.kebab(value);
case "dot":
return Case.lower(value, ".", true);
default:
return Case[expectedCase](value);
}
}
function isObjectObject(val) {
return val != null && typeof val === "object" && Array.isArray(val) === false;
}
export function isPlainObject(o) {
if (isObjectObject(o) === false)
return false;
// If has modified constructor
const ctor = o.constructor;
if (typeof ctor !== "function")
return false;
// If has modified prototype
const prot = ctor.prototype;
if (isObjectObject(prot) === false)
return false;
// If constructor does not have an Object-specific method
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
return false;
}
// Most likely a plain Object
return true;
}
export function isEmptyObject(value) {
return isObjectObject(value) && Object.keys(value).length === 0;
}
/**
* Creates an object with the same keys as object and values generated by running each own enumerable
* string keyed property of object thru iteratee.
*
* Inspired on lodash.mapValues, see https://lodash.com/docs/4.17.15#mapValues
*/
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export function mapValues(obj, iteratee) {
const output = {};
for (const [key, value] of Object.entries(obj)) {
output[key] = iteratee(value, key);
}
return output;
}
export function objectToExpectedCase(obj, expectedCase = "camel") {
if (Array.isArray(obj)) {
const newArr = [];
for (let i = 0; i < obj.length; i++) {
newArr[i] = objectToExpectedCase(obj[i], expectedCase);
}
return newArr;
}
if (Object(obj) === obj) {
const newObj = {};
for (const name of Object.getOwnPropertyNames(obj)) {
const newName = toExpectedCase(name, expectedCase);
if (newName !== name && Object.prototype.hasOwnProperty.call(obj, newName)) {
throw new Error(`object already has a ${newName} property`);
}
newObj[newName] = objectToExpectedCase(obj[name], expectedCase);
}
return newObj;
}
return obj;
}
//# sourceMappingURL=objects.js.map