topkat-utils
Version:
A comprehensive collection of TypeScript/JavaScript utility functions for common programming tasks. Includes validation, object manipulation, date handling, string formatting, and more. Zero dependencies, fully typed, and optimized for performance.
122 lines (121 loc) • 8.75 kB
TypeScript
import { ObjectGeneric } from './types';
/** Return an object:
* * with only selected fields
* * OR without masked fields
*/
export declare function simpleObjectMaskOrSelect<Obj extends ObjectGeneric>(object: Obj, maskedOrSelectedFields: (keyof Obj)[], mode?: 'mask' | 'select', deleteKeysInsteadOfReturningAnewObject?: boolean): Obj;
/**
* check if **object OR array** has property Safely (avoid cannot read property x of null and such)
* @param {Object} obj object to test against
* @param {string} addr `a.b.c.0.1` will test if myObject has props a that has prop b. Work wit arrays as well (like `arr.0`)
*/
export declare function has(obj: ObjectGeneric, addr: string): boolean | undefined;
/** Find address in an object "a.b.c" IN { a : { b : {c : 'blah' }}} RETURNS 'blah'
* @param obj
* @param addr accept syntax like "obj.subItem.[0].sub2" OR "obj.subItem.0.sub2" OR "obj.subItem[0].sub2"
* @returns the last item of the chain OR undefined if not found
*/
export declare function findByAddress(obj: ObjectGeneric, addr: string | string[]): any | undefined;
type FindByAddressReturnFull = Array<[addr: string, value: any, lastElmKey: string, parent: any[] | Record<string, any>]>;
/** Will return all objects matching that path. Eg: user.*.myVar */
export declare function findByAddressAll<ReturnAddresses extends boolean = false>(obj: Record<string, any>, addr: string, returnAddresses?: ReturnAddresses): ReturnAddresses extends true ? FindByAddressReturnFull : Array<any>;
/** Enforce writing subItems. Eg: user.name.blah will ensure all are set until the writing of the last item
* NOTE: doesn't work when parent is array
*/
export declare function objForceWrite<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item: any, options?: {
doNotWriteFinalValue?: boolean;
}): MainObj;
export declare function forcePathInObject<MainObj extends Record<string, any>>(obj: MainObj, addr: string): MainObj;
export declare const objForceWritePath: typeof forcePathInObject;
/** Enforce writing subItems, only if obj.addr is empty.
* Eg: user.name.blah will ensure all are set until the writing of the last item
* if user.name.blah has a value it will not change it.
* NOTE: doesn't work when parent is array
*/
export declare function objForceWriteIfNotSet<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item: any): MainObj;
/** Merge mixins into class. Use it in the constructor like: mergeMixins(this, {myMixin: true}) */
export declare function mergeMixins(that: any, ...mixins: any[]): void;
export declare function cloneObject<MainObj extends Record<string, any>>(o: MainObj): MainObj;
/** Deep clone. WILL REMOVE circular references */
export declare function deepClone<MainObj extends Record<string, any>>(obj: MainObj, cache?: never[]): MainObj;
/**
* @param {Object} obj the object on which we want to filter the keys
* @param {function} filterFunc function that returns true if the key match the wanted criteria
*/
export declare function filterKeys<MainObj extends Record<string, any>>(obj: MainObj, filter: any): MainObj;
/**
* @param {Object} obj the object on which we want to delete a property
* @param {Array} addrArr addressArray on which to delete the property
*/
export declare function deleteByAddress(obj: object, addr: string | string[]): void;
/** Remove all key/values pair if value is undefined */
export declare function objFilterUndefined<MainObj extends Record<string, any>>(o: MainObj): MainObj;
/** Lock all 1st level props of an object to read only */
export declare function readOnly<MainObj extends Record<string, any>>(o: MainObj): {
readonly [AA in keyof MainObj]: MainObj[AA];
};
/** Fields of the object can be created BUT NOT reassignated */
export declare function reassignForbidden(o: any): any;
/** All fileds and subFields of the object will become readOnly */
export declare function readOnlyRecursive(object: any): any;
/** @deprecated use readOnlyRecursive instead */
export declare const readOnlyForAll: typeof readOnlyRecursive;
export declare function objFilterUndefinedRecursive(obj: any): any;
export declare function sortObjKeyAccordingToValue(unorderedObj: any, ascending?: boolean): {};
/**
* Make default value if object key do not exist
* @param {object} obj
* @param {string} addr
* @param {any} defaultValue
* @param {function} callback (obj[addr]) => processValue. Eg: myObjAddr => myObjAddr.push('bikou')
* @return obj[addr] eventually processed by the callback
*/
export declare function ensureObjectProp<MainObj extends Record<string, any>, Addr extends string>(obj: MainObj, addr: Addr, defaultValue: any, callback: (o: any) => any): MainObj[Addr];
/** object and array merge
* @warn /!\ Array will be merged and duplicate values will be deleted /!\
* @return {Object} new object result from merge
* NOTE: objects in params will NOT be modified*/
export declare function mergeDeep<O1 extends Record<string, any>, O2 extends Record<string, any> = Record<string, any>, O3 extends Record<string, any> = Record<string, any>, O4 extends Record<string, any> = Record<string, any>, O5 extends Record<string, any> = Record<string, any>, O6 extends Record<string, any> = Record<string, any>>(...objects: [O1, O2?, O3?, O4?, O5?, O6?]): O1 & O2 & O3 & O4 & O5 & O6;
/** object and array merge
* @warn /!\ Array will be replaced by the latest object /!\
* @return {Object} new object result from merge
* NOTE: objects in params will NOT be modified */
export declare function mergeDeepOverrideArrays<O1 extends Record<string, any>, O2 extends Record<string, any> = Record<string, any>, O3 extends Record<string, any> = Record<string, any>, O4 extends Record<string, any> = Record<string, any>, O5 extends Record<string, any> = Record<string, any>, O6 extends Record<string, any> = Record<string, any>>(...objects: [O1, O2?, O3?, O4?, O5?, O6?]): O1 & O2 & O3 & O4 & O5 & O6;
/** object and array merge
* @param {Function} replacerForArrays item[key] = (prevValue, currentVal) => () When 2 values are arrays,
* @param {Function} replacerForObjects item[key] = (prevValue, currentVal) => () When 2 values are objects,
* @param {Function} replacerDefault item[key] = (prevValue, currentVal) => () For all other values
* @param {...Object} objects
* @return {Object} new object result from merge
* NOTE: objects in params will NOT be modified
*/
export declare function mergeDeepConfigurable<O1 extends Record<string, any>, O2 extends Record<string, any> = Record<string, any>, O3 extends Record<string, any> = Record<string, any>, O4 extends Record<string, any> = Record<string, any>, O5 extends Record<string, any> = Record<string, any>, O6 extends Record<string, any> = Record<string, any>>(replacerForArrays: ((_: any, curr: any) => any) | undefined, replacerForObjects: any, replacerDefault: ((_: any, curr: any) => any) | undefined, ...objects: [O1, O2?, O3?, O4?, O5?, O6?]): O1 & O2 & O3 & O4 & O5 & O6;
/** { a: {b:2}} => {'a.b':2} useful for translations
* NOTE: will remove circular references
*/
export declare function flattenObject(data: any, config?: {
withoutArraySyntax?: boolean;
withArraySyntaxMinified?: boolean;
}): Record<string, any>;
/** {'a.b':2} => { a: {b:2}} */
export declare function unflattenObject(data: Record<string, any>): Record<string, any>;
/** Mean to fix typing because type for Object.entries is not accurate. Ref: https://stackoverflow.com/questions/66565322/get-type-keys-in-typescript
* /!\ THIS WILL REMOVE SYMBOL AND NUMBER FROM KEY TYPES as this is 99% of the time unwanted for generic objects
*/
export declare function objEntries<Obj extends Record<string, any>>(obj: Obj): ObjEntries<Obj>;
/** Will remove Symbol and Number from keys types */
type ObjEntries<T, K extends keyof T = keyof T> = (K extends string ? [K, T[K]] : never)[];
/** Will remove Symbol and Number from keys types */
type StringKeys<T> = keyof T extends infer K ? K extends string ? K : never : never;
/** Mean to fix typing because type for Object.keys is not accurate */
export declare function objKeys<Obj extends Record<string, any>>(obj: Obj): StringKeys<Obj>[];
/** Will merge all arrays of an object into a single array */
export declare function mergeObjectArrays<T extends Record<string, any[]>>(obj: T): T[keyof T][number][];
export declare const keys: typeof objKeys;
export declare const entries: typeof objEntries;
/** A Helper to create JavascriptProxies, will add __isProxy and toJSON helper to prevent error when logging the proxy and to be able to check if the object is proxyfied */
export declare function createProxy<T extends Record<string, any>>(obj: T, optn: {
get: Required<ProxyHandler<T>>['get'];
jsonRepresentation?: (obj: T) => string;
}): T;
export {};