@techmely/utils
Version:
Collection of helpful JavaScript / TypeScript utils
119 lines (114 loc) • 2.73 kB
JavaScript
/*!
* @techmely/utils
* Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com>
* MIT Licensed
*/
import {
camel2snake
} from "./chunk-R2WJ4MZS.mjs";
import {
isArray,
isDef,
isNotEmpty,
isNotNull,
isObject,
isUndef
} from "./chunk-BD32CMSL.mjs";
// src/object.ts
function deepMerge(target, ...sources) {
if (sources.length === 0) {
return target;
}
const source = sources.shift();
if (source === void 0) {
return target;
}
if (isMergeableObject(target) && isMergeableObject(source)) {
const sourceKeys = Object.keys(source);
for (const key of sourceKeys) {
if (isMergeableObject(source[key])) {
if (!target[key]) {
target[key] = {};
}
if (isMergeableObject(target[key])) {
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
} else {
target[key] = source[key];
}
}
}
return deepMerge(target, ...sources);
}
function isMergeableObject(item) {
return isObject(item) && !isArray(item);
}
function removeEmptyObj(obj) {
return Object.fromEntries(
Object.entries(obj).filter(([_, v]) => isNotNull(v) && isDef(v) && isNotEmpty(v))
);
}
function removeUndefObj(obj) {
const keys = Object.keys(obj);
for (const key of keys) {
isUndef(obj[key]) ? obj[key] === void 0 : {};
}
return obj;
}
function objectMap(obj, fn) {
return Object.fromEntries(
// @ts-expect-error ignore type check
Object.entries(obj).map(([k, v]) => fn(k, v)).filter(isNotNull)
);
}
function isKeyOf(obj, k) {
return k in obj;
}
function objectKeys(obj) {
return Object.keys(obj);
}
function objectEntries(obj) {
return Object.entries(obj);
}
function objectCamel2Snake(obj) {
return Object.entries(obj).reduce(
// biome-ignore lint/performance/noAccumulatingSpread: Ignore here
(acc, cur) => ({ ...acc, [camel2snake(cur[0])]: cur[1] }),
{}
);
}
function pick(state, paths) {
if (Array.isArray(paths)) {
return paths.reduce((acc, path) => {
const _paths = path.split(".");
return set(acc, _paths, get(state, _paths));
}, {});
}
return get(state, paths.split("."));
}
function get(state, paths) {
return paths.reduce((acc, path) => acc?.[path], state);
}
var ProtoRE = /^(__proto__)$/;
function set(state, paths, val) {
const last = paths.at(-1);
if (last === void 0)
return state;
const restPaths = paths.slice(0, -1);
const result = restPaths.reduce((obj, p) => ProtoRE.test(p) ? {} : obj[p] ||= {}, state);
result[last] = val;
return state;
}
export {
deepMerge,
removeEmptyObj,
removeUndefObj,
objectMap,
isKeyOf,
objectKeys,
objectEntries,
objectCamel2Snake,
pick
};