Socket
Socket
Sign inDemoInstall

js-awe

Package Overview
Dependencies
Maintainers
0
Versions
72
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

js-awe - npm Package Compare versions

Comparing version 1.0.67 to 1.0.68

770

dist/browser/js-awe.min.d.ts

@@ -31,9 +31,21 @@ import * as F from 'fluture';

* Create event/s and start the timer.
* @param eventNames name of the event or array with events
* @param eventNames Name of the event or array with event names.
* @example
* // Single event
* chrono.time('step1');
*
* // Multiple events
* chrono.time(['step1', 'step2']);
*/
time(eventNames: string | string[]): void
time(eventNames: string | string[]): void;
/**
* Stop the timer for the envent/s.
* @param eventNames name of the event or array with events
* Stop the timer for the event/s.
* @param eventNames Name of the event or array with event names.
* @example
* // Single event
* chrono.timeEnd('step1');
*
* // Multiple events
* chrono.timeEnd(['step1', 'step2']);
*/

@@ -43,34 +55,3 @@ timeEnd(eventNames: string | string[]): void

/**
* console.log the following report below:
* ```
* chronoCreation : 2023-11-05T11:50:54.798Z
* report : 2023-11-05T11:50:56.119Z
*
* Timeline of events:
* ┌────────┬───────────────────────────────────────────────────────────────────────────────────────┐
* │ Events │ ms 0 656 1198 1300 │
* ├────────┼───────────────────────────────────────────────────────────────────────────────────────┤
* │ step1 │ |--------------------------------------| || │
* │ step2 │ |------------------------------------| │
* │ step3 │ |-----------------------------| │
* └────────┴───────────────────────────────────────────────────────────────────────────────────────┘
*
* Total elapse Time of each event:
* ┌───────┬────────┬────────────┐
* │ name │ elapse │ percentage │
* ├───────┼────────┼────────────┤
* │ step1 │ 655 │ 36.85 │
* │ step2 │ 620 │ 34.86 │
* │ step3 │ 503 │ 28.29 │
* └───────┴────────┴────────────┘
*
* Coinciding Events timeline:
* ┌───────────────┬──────────┬────────────┐
* │ runningEvents │ elapseMs │ percentage │
* ├───────────────┼──────────┼────────────┤
* │ step1 │ 655 │ 51.39 │
* │ step2 │ 116 │ 9.16 │
* │ step2,step3 │ 503 │ 39.45 │
* └───────────────┴──────────┴────────────┘
* ```
* Print the report of the events in the console.
*/

@@ -80,5 +61,14 @@ report(): void

/**
* This is an implementation of Chrono().time() to use in pipeline of functions. Prepaire the time event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes data is passed to the next function. This function
* This is an implementation of Chrono().time() to use in a pipeline of functions. Prepare the time event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes, data is passed to the next function. This function
* takes the input and passes it to the next function without modifications.
* @param event Name of the event or array with event names.
* @returns A function that takes the input data and passes it to the next function without modifications.
* @example
* const pipeline = [
* chrono.setTime('step1'),
* // other functions in the pipeline
* ];
*
* const result = pipeline.reduce((data, fn) => fn(data), inputData);
*/

@@ -88,5 +78,14 @@ setTime: (event: string | string[]) => <T>(data: T) => T;

/**
* This is an implementation of Chrono().timeEnd() to use in pipeline of functions. Prepaire the timeEnd event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes data is passed to the next function. This function
* This is an implementation of Chrono().timeEnd() to use in a pipeline of functions. Prepare the timeEnd event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes, data is passed to the next function. This function
* takes the input and passes it to the next function without modifications.
* @param event Name of the event or array with event names.
* @returns A function that takes the input data and passes it to the next function without modifications.
* @example
* const pipeline = [
* // other functions in the pipeline
* chrono.setTimeEnd('step1'),
* ];
*
* const result = pipeline.reduce((data, fn) => fn(data), inputData);
*/

@@ -96,10 +95,36 @@ setTimeEnd: (event: string | string[]) => <T>(data: T) => T;

/**
* This is an implementation of Chrono().report() to use in pipeline of functions. Its execution will log the event reports as in
* This is an implementation of Chrono().report() to use in a pipeline of functions. Its execution will log the event reports as in
* Chrono().report() and returns the same data received as input.
* @returns A function that takes the input data, logs the event reports, and returns the same data.
* @example
* const pipeline = [
* // other functions in the pipeline
* chrono.logReport,
* ];
*
* const result = pipeline.reduce((data, fn) => fn(data), inputData);
*/
logReport: <T>(data: T) => T;
/**
* Get the current state of the Chrono timer.
* @returns The current state of the Chrono timer.
*/
getChronoState: () => {};
/**
* Set the Chrono timer state using the Performance API format.
* @param performanceGetEntriesByTypeOjb The Performance API object returned by `performance.getEntriesByType('measure')`.
*/
setChronoStateUsingPerformanceAPIFormat: (performanceGetEntriesByTypeOjb: any) => void;
/**
* Get the Chrono timer state using the Performance API format.
* @returns The Chrono timer state in the Performance API format.
*/
getChronoStateUsingPerformanceAPIFormat: () => any[];
/**
* Calculate the average time for each event.
*/
average: () => void;

@@ -125,62 +150,78 @@ }

/**
* @fileoverview TypeScript declarations for jsUtils module.
* @module jsUtils
*/
/**
* Utility functions for JavaScript.
* @namespace jsUtils
*/
/**
* Logs a message with a prefix.
* @param {any} title - The prefix for the log message.
* @param {any} displayFunc - The function to display the log message.
* @returns {Function} - The log function.
*/
declare function logWithPrefix(title: any, displayFunc: any): (message: any) => any;
/**
* Capitalizes the first letter of a string.
* @param {any} str - The string to capitalize.
* @returns {any} - The capitalized string.
*/
declare function firstCapital(str: any): any;
/**
* String template funcionality. Given a string with "text {{var1}} text2 {{var2}}""
* and an state object {var1: 'fool', var2: 'bar'}. It returns a string substituting
* the template variables for its value. "text fool text2 bar""
* state can be a string, an object or an array.
* For mode=url a state array is converted into a list of values separated by comma.
* For mode=url a state object is converted into query field=value separated by &
* If mode is different to url. state is stringigify.
* @example
* ```
* varSubsDoubleBracket(`
* {
* "id": 1231,
* "description": "{{description=\"This is a test\"}}",
* "car": "{{plate}}",
* }`, {plate:{a:3}}) //?
* ```
* This will produce
* ```
* `{
* "id": 1231,
* "description": "{{description=\"This is a test\"}}",
* "car": {a:3},
* }`
* ```
* varSubsDoubleBracket('https://bank.account?account={{account}}', {account:['10232-1232','2331-1233']},'url')
* https://bank.account?account=10232-1232,2331-1233
*
* varSubsDoubleBracket('https://bank.account?{{params}}', {params:{a:'10232-1232',b:'2331-1233'}},'url')
* https://bank.account?a=10232-1232&b=2331-1233}
*
* @param strToResolveVars string with variables to be substituted. The string can represent a Json or url.
* @param state state with the values to substitute the template vars.
* @param mode: url: for converting state arrays into separated comma field=value1,value2
* and objects into field=value & field2=value2. if mode is not specified: state is stringify.
* @returns string after substituting the template vars for its corresponding values from state object.
* String template functionality. Given a string with "text {{var1}} text2 {{var2}}"
* and a state object {var1: 'foo', var2: 'bar'}, it returns a string substituting
* the template variables for their values. "text foo text2 bar"
* The state can be a string, an object, or an array.
* For mode=url, a state array is converted into a list of values separated by commas.
* For mode=url, a state object is converted into query field=value separated by '&'.
* If mode is different from 'url', the state is stringified.
* @param {string} strToResolveVars - The string with variables to be substituted. The string can represent a JSON or URL.
* @param {any} state - The state with the values to substitute the template variables.
* @param {string} [mode] - The mode for converting the state. 'url' for converting state arrays into comma-separated field=value1,value2
* and objects into field=value & field2=value2. If mode is not specified, the state is stringified.
* @returns {string} - The string after substituting the template variables for their corresponding values from the state object.
*/
declare function varSubsDoubleBracket(strToResolveVars: string, state: any, mode?: 'url'): string;
/**
* Converts a query object to a string representation.
* @param {any} query - The query object to convert.
* @returns {string} - The string representation of the query object.
*/
declare function queryObjToStr(query: any): string;
/**
* Custom error class that extends the Error class.
* @extends Error
*/
declare class CustomError extends Error {
constructor(name?: string, message?: string, data?: {
status: number;
});
data: {
status: number;
};
/**
* Creates an instance of CustomError.
* @param {string} [name='GENERIC'] - The name of the error.
* @param {string} message - The message of the error.
* @param {object} [data={ status: 500 }] - Additional data about the error.
*/
constructor(name?: string, message?: string, data?: { status: number });
data: { status: number };
}
/**
* Creates a custom error class with the given error name.
* @param {string} errorName - The name of the custom error class.
* @returns {object} - The custom error class.
*/
declare function createCustomErrorClass(errorName: string): {
new (name?: string, message?: string, data?: { status: number}): {
name: string;
data: {
status: number;
};
map(func: Function): any;
chain(func: Function): any;
message: string;
stack?: string;
new (name?: string, message?: string, data?: { status: number }): {
name: string;
data: { status: number };
map(func: Function): any;
chain(func: Function): any;
message: string;
stack?: string;
};

@@ -192,2 +233,10 @@ of: typeof CustomError;

};
/**
* Composes a URL from the gateway URL, service name, and service path.
* @param {any} gatewayUrl - The gateway URL.
* @param {any} serviceName - The service name.
* @param {any} servicePath - The service path.
* @returns {object} - The composed URL object.
*/
declare function urlCompose(gatewayUrl: any, serviceName: any, servicePath: any): {

@@ -199,4 +248,24 @@ gatewayUrl: any;

};
/**
* Decomposes a URL into the gateway URL, service name, and service path.
* @param {any} url - The URL to decompose.
* @param {any} listOfServiceNames - The list of service names.
* @returns {any} - The decomposed URL object.
*/
declare function urlDecompose(url: any, listOfServiceNames: any): any;
/**
* Returns the index of the nth match of a substring in a string.
* @param {any} string - The string to search in.
* @param {any} toMatch - The substring to match.
* @param {any} nth - The nth match to find.
* @returns {any} - The index of the nth match.
*/
declare function indexOfNthMatch(string: any, toMatch: any, nth: any): any;
/**
* Namespace for color constants.
* @namespace colors
*/
declare namespace colors {

@@ -232,101 +301,290 @@ const red: string;

}
/**
* Colors a message with the specified color.
* @param {any} message - The message to color.
* @param {any} color - The color to apply.
* @returns {string} - The colored message.
*/
declare function colorMessage(message: any, color: any): string;
/**
* Colors a message based on the status.
* @param {any} message - The message to color.
* @param {any} status - The status to determine the color.
* @returns {string} - The colored message.
*/
declare function colorMessageByStatus(message: any, status: any): string;
/**
* Gets the color based on the status.
* @param {any} status - The status to determine the color.
* @returns {string} - The color.
*/
declare function colorByStatus(status: any): string;
/**
* Finds the deep key in an object.
* @param {any} objIni - The initial object.
* @param {any} keyToFind - The key to find.
* @returns {any[]} - The array of found keys.
*/
declare function findDeepKey(objIni: any, keyToFind: any): any[];
/**
* Freezes an object deeply.
* @param {any} o - The object to freeze.
* @returns {any} - The frozen object.
*/
declare function deepFreeze(o: any): any;
/**
* Gets the value at the specified path in an object.
* @param {any} obj - The object to get the value from.
* @param {any} valuePath - The path to the value.
* @returns {any} - The value at the specified path.
*/
declare function getAt(obj: any, valuePath: any): any;
/**
* Sets the value at the specified path in an object.
* @param {any} obj - The object to set the value in.
* @param {any} valuePath - The path to the value.
* @param {any} value - The value to set.
* @returns {string} - The result of setting the value.
*/
declare function setAt(obj: any, valuePath: any, value: any): string;
/**
* Creates a sorter function to use as a parameter in array.prototype.sort(sorter).
* It can order by several fields. If fields are equal, it will uneven using subsequent fields.
* @param {any} paths - List of paths to sort by. One path for each field to order by. Route path is of the shape 'person.details.age'. If it is only one field, it can be a string.
* @param {boolean} [isAsc=true] - Optional. Default: true. true: to order ascending. false: to order descending.
* @returns {Function} - A sorter function to include in array.prototype.sort(sorter).
*/
declare function sorterByPaths(paths: any, isAsc?: boolean): (objA: any, objB: any) => number;
/**
* Create a sorter function to use as a parameter in array.prototype.sort(sorter):
* It can order by several fields. If fields are equal it will uneven using
* subsequent fields.
* @param paths List of paths to sort by. One path for each field to order by. Route path is
* of the shape. ex: 'person.details.age'. If it is only one field it can be a string.
* @param isAsc Optional. Default: true. true: to order ascending. false: to order descending
* @returns Return a sorter function to include in array.prototype.sort(sorter)
* Filters and maps an array.
* @param {any} mapWithUndefinedFilterFun - The array to filter and map.
* @param {any} data - The data to filter and map.
* @returns {any[]} - The filtered and mapped array.
*/
declare function sorterByPaths(paths: any, isAsc?: boolean): (objA: any, objB: any) => number;
declare function filterFlatMap(mapWithUndefinedFilterFun: any, data: any): any[];
/**
* Sorts an array in ascending or descending order.
* @param {boolean} [isAsc=true] - Optional. Default: true. true: to order ascending. false: to order descending.
* @returns {Function} - A sorter function to use with array.prototype.sort(sorter).
*/
declare function arraySorter(isAsc?: boolean): (a: any, b: any) => 1 | -1 | 0;
/**
* Checks if an object is a Promise.
* @param {any} obj - The object to check.
* @returns {boolean} - true if the object is a Promise, false otherwise.
*/
declare function isPromise(obj: any): boolean;
declare function sleep(ms: any): Promise<any>;
declare function sleepWithValue(ms: any, value: any): Promise<any>;
declare function sleepWithFunction(ms: any, func: any, ...params: any[]): Promise<any>;
declare function notTo(funct: any): (...params: any[]) => boolean;
declare function arrayToObject(arr: any, defaultValueFunction: any): any;
/**
* Sleeps for the specified number of milliseconds.
* @param {number} ms - The number of milliseconds to sleep.
* @returns {Promise<any>} - A Promise that resolves after the specified number of milliseconds.
*/
declare function sleep(ms: number): Promise<any>;
/**
* Sleeps for the specified number of milliseconds and resolves with the specified value.
* @param {number} ms - The number of milliseconds to sleep.
* @param {any} value - The value to resolve with.
* @returns {Promise<any>} - A Promise that resolves after the specified number of milliseconds with the specified value.
*/
declare function sleepWithValue(ms: number, value: any): Promise<any>;
/**
* Sleeps for the specified number of milliseconds and executes the specified function with the specified parameters.
* @param {number} ms - The number of milliseconds to sleep.
* @param {Function} func - The function to execute.
* @param {...any} params - The parameters to pass to the function.
* @returns {Promise<any>} - A Promise that resolves after the specified number of milliseconds with the result of the function.
*/
declare function sleepWithFunction(ms: number, func: Function, ...params: any[]): Promise<any>;
/**
* Negates a function.
* @param {Function} funct - The function to negate.
* @returns {Function} - The negated function.
*/
declare function notTo(funct: Function): (...params: any[]) => boolean;
/**
* Converts an array to an object using the specified default value function.
* @param {any} arr - The array to convert.
* @param {Function} defaultValueFunction - The function to generate the default value.
* @returns {any} - The converted object.
*/
declare function arrayToObject(arr: any, defaultValueFunction: Function): any;
/**
* Converts an array of objects to an object.
* @param {any} iterable - The array of objects to convert.
* @returns {any} - The converted object.
*/
declare function arrayOfObjectsToObject(iterable: any): any;
/**
* Removes duplicates from an array.
* @param {any} arr - The array to remove duplicates from.
* @returns {any[]} - The array without duplicates.
*/
declare function removeDuplicates(arr: any): any[];
/**
* Traverses an object and applies a reviver function to each node.
* @param {any} objIni - The object to traverse.
* @param {Function} reviver - The function to be called for each node.
* @param {boolean} [pureFunction] - true: work with a deep clone of objIni, false: work with objIni passed as a parameter.
* @returns {any} - The object after applying the reviver actions.
*/
declare function traverse(objIni: any, reviver: (value: any, path: string[], parent: any, prop: string) => any, pureFunction?: boolean): any;
/**
* Access each node of the object calling the reviver function. Reviver can return:
* undefined: no change
* traverse.skip: stop accessing subtrees
* traverse.stop: stop completly the object traverse
* traverse.delete: delete the current node
* traverse.match(stringQuery, reviverPath) return true if reviverPath match query string
*
* @param objIni The object to traverse.
* @param reviver The function to be called for each node
* @pureFunction true: work with a deepClone of objIni, false: work with objIni passed as a parameter.
* @returns Return the object after applying reviver actions
* Symbol to skip traversing a subtree.
* @type {symbol}
*/
declare function traverse(objIni: any, reviver: (value: any, path: string[], parent: any, prop: string) => any, pureFunction?: boolean): any
declare namespace traverse {
export const skip: symbol;
export const stop: symbol;
const _delete: symbol;
export { _delete as delete };
}
declare const skip: symbol;
/**
* Takes vertifical slices of a two nested array and calls functionToRun with each slice
* Symbol to stop traversing the object.
* @type {symbol}
*/
declare const stop: symbol;
/**
* Symbol to delete the current node.
* @type {symbol}
*/
declare const _delete: symbol;
/**
* Takes vertical slices of a two-nested array and calls a function with each slice.
* @param {Function} functionToRun - The function to run with each vertical slice.
* @param {string[]} verFields - The fields inside each item of the traverse array that contains the second nested arrays to iterate vertically.
* @param {any[]} toTraverse - The array to traverse.
* @returns {void}
*/
declare function traverseVertically(functionToRun: (verticalSlice: object, runIndex: number) => any, verFields: string[], toTraverse: any[]): void;
/**
* Projects a subset of a JSON object based on specified paths, optionally removing properties marked for deletion.
*
* @param {string[]} paths - An array of strings representing the paths to the properties in the JSON object that should be included in the output.
* @param {Object} json - The JSON object from which the properties specified by paths will be extracted.
* @param {boolean} [removeWithDelete=true] - A boolean indicating whether properties in the JSON object marked with a specific delete flag should be removed from the output. Defaults to true, meaning properties marked for deletion will be removed.
*
* @returns {Object} A new JSON object containing only the properties specified by the paths array. If removeWithDelete is true, any properties marked for deletion will not be included in the returned object.
*
* @example
* ```
* traverseVertically (
* functionToRun
* ['marathonResults'], // List of fields for the second level nested array
* [{name:'Jose',marathonResults:[12,35]},{name:'Ana',marathonResults:[1]}]
* )
* ```
* This will produce folllowing calls
* ```
* functionToRun([{name:'Jose', marathonResults:12}, {name:'Ana',marathonResults:1}])
* functionToRun([{name:'Jose', marathonResults:35}, {name:'Ana',marathonResults:undefined}])
* ```
*
* @param functionToRun This function will be called for each vertical slice.
* @param verFields Fields inside each item of the traverse array that contains the second nested arrays to iterate vertically.
* @param toTraverse: Array to be traverse
* @returns void
* // Assuming a JSON object `data` as follows:
* // {
* // user: {
* // name: "John Doe",
* // age: 30,
* // email: "johndoe@example.com",
* // _delete: { email: true }
* // }
* // }
* // And calling the function with paths to include the user's name and email:
* project(['user.name', 'user.email'], data);
* // Returns: { user: { name: "John Doe" } }
* // Note: The email property is not included in the output because it's marked for deletion.
*/
declare function traverseVertically(functionToRun: (verticalSlice: object, runIndex: number) => any, verFields: string[], toTraverse: any[]): void
declare function project(paths: string[], json: any): any
/**
* Totally recreate a new object with the selected values using jsonpath-plus format for queries.
* Given objDest and shouldUpdateOnlyEmptyFields generates function that expect inputObj to copy all properties from inputObj to objDest.
*
* @param paths Array with the queries for the projection. First char must be + to include or - to remove
* @param json Subject object to project.
* @param {Object} objDest Destination object for the copy.
* @param {boolean} shouldUpdateOnlyEmptyFields? true: does not replace destination fields with values.
* @example
* // returns {a:{b:{c:3,e:9}}}
* project(['+$.a.b','-$.a.b.d'], {a:{b:{c:3,d:5,e:9}}});
* @returns any
* // returns {isin:123456, name:'test'}
* copyPropsWithValue({isin:123456}, true)({isin:123, name:'test'});
* // returns {isin:123, name:'test'}
* copyPropsWithValue({isin:123456}, false)({isin:123, name:'test'});
* @returns {Function} A function that takes an input object for props to be copied in objDest.
*/
declare function project(paths:string[], json:any):any
declare function copyPropsWithValue(objDest: any, shouldUpdateOnlyEmptyFields?: boolean): (input: any) => any;
declare function copyPropsWithValue(objDest: any, shouldUpdateOnlyEmptyFields?: boolean): (inputObj: any) => any;
/**
* Given objDest, copyRules and shouldUpdateOnlyEmptyFields generates function that expect input object to copy only properties indicated by copyRules from inputObj to objDest.
*
* @param {Object} objDest - The destination object to copy properties into.
* @param {Array<string|Object>} copyRules - An array of rules specifying which properties to copy.
* Each rule can be either a string (for same-named properties) or an object with 'from' and 'to' keys.
* @param {boolean} [shouldUpdateOnlyEmptyFields=false] - If true, only update fields in the destination object that are empty.
* @returns {Function} A function that takes an input object for props to be copied in objDest.
*
* @example
* let objTo = {a:{b:2},c:3};
* let objFrom = {a:{b:4},c:8,d:{e:{f:12}}};
* copyPropsWithValueUsingRules(objTo, [{from:'a.b', to:'c'}, {from:'d.e.f', to:'d'}])(objFrom);
* // objTo is now {a:{b:2},c:4,d:12}
*
* @example
* let objTo = {a:{b:2},c:3};
* let objFrom = {a:{b:4},c:8,d:{e:{f:12}}};
* copyPropsWithValueUsingRules(objTo, [{from:'a.b', to:'c'}, {from:'d.e.f', to:'d.f'}, {from:'d.e.g', to:'d.g'}], true)(objFrom);
* // objTo is now {a:{b:2},c:3,d:{f:12}}
*/
declare function copyPropsWithValueUsingRules(objDest: any, copyRules: any, shouldUpdateOnlyEmptyFields?: boolean): (inputObj: any) => any;
declare class EnumMap {
/**
* Creates an instance of EnumMap.
* @param {object} values - The values of the enum.
*/
constructor(values: any);
/**
* A Proxy handler method for getting a property value.
*/
get(target: any, prop: any): any;
/**
* A Proxy handler method for setting a property value.
*/
set(_undefined: any, prop: any): void;
/**
* Gets the current active value of the enum.
* @returns {string} The active enum value.
*/
invert(): EnumMap;
}
declare class Enum {
constructor(values: any, rules: any);
/**
* Creates an instance of Enum.
* @param {Array<string>} values - The values of the enum.
* @param {object} rules - The rules defining valid transitions between enum values.
*/
constructor(values: Array<string>, rules: object);
/**
* A Proxy handler method for getting a property value.
*/
get: (_target: any, prop: any) => any;
/**
* A Proxy handler method for setting a property value.
*/
set: (_undefined: any, prop: any, value: any) => boolean;
getValue: () => any;
/**
* Gets the current active value of the enum.
* @returns {string} The active enum value.
*/
getValue: () => string;
}
/**
* Creates a state machine transition function.
* @param {object} states - The states of the state machine.
* @param {object} events - The events of the state machine.
* @param {object} transitions - The transitions of the state machine.
* @returns {Function} A function that transitions the state machine.
*/
declare function transition(states: any, events: any, transitions: any): {

@@ -336,5 +594,64 @@ (event: any): any;

};
declare function pushUniqueKey(row: any, table: any, indexes?: number[]): any;
/**
* Pushes a unique key into a table.
* @param row
* @param table
* @param indexes
* @returns
* @example
* ```
* pushUniqueKey({id: 1, name: 'John'}, [{id: 1, name: 'John'}], [0]) //?
* ```
* This will produce
* ```
* [{id: 1, name: 'John'}]
* ```
*/
declare function pushUniqueKey(row: any, table: any[], indexes?: number[]): any;
/**
* Pushes a unique key into a table or changes the existing row.
* @param newRow
* @param table
* @param indexes
* @param mergeFun
* @returns
* @example
* ```
* pushUniqueKeyOrChange({id: 1, name: 'John'}, [{id: 1, name: 'John'}], [0], (oldRow, newRow) => ({...oldRow, ...newRow})) //?
* ```
* This will produce
* ```
* [{id: 1, name: 'John'}]
* ```
*/
declare function pushUniqueKeyOrChange(newRow: any, table: any, indexes: number[], mergeFun: any): any;
/**
* Pushes a value at a given position in an array.
* @param pos
* @param value
* @param arr
* @returns
* @example
* ```
* pushAt(1, 'a', ['b', 'c']) //?
* ```
* This will produce
* ```
* ['b', 'a', 'c']
* ```
*/
declare function pushAt(pos: any, value: any, arr: any): any;
/**
* Memoizes a function.
* @returns
* @example
* ```
* const memoizeMap = memoize().memoizeMap;
* const memoizeWithHashFun = memoize().memoizeWithHashFun;
* ```
*/
declare function memoize(): {

@@ -344,2 +661,17 @@ memoizeMap: (func: any, ...params: any[]) => any;

};
/**
* Fills an array with a given value.
* @param mapper
* @param lenOrWhileTruthFun
* @returns
* @example
* ```
* fillWith('a', 3) //?
* ```
* This will produce
* ```
* ['a', 'a', 'a']
* ```
*/
declare function fillWith(mapper: any, lenOrWhileTruthFun: any): any[];

@@ -352,8 +684,48 @@

declare function isDate(d: any): boolean;
/**
* Checks if a value is empty: undefined, null, '', 0, NaN, [], {}
* empty is bigger than falsy as we have added [] and {} that are truthy
* @param value - The value to check.
* @returns Returns `true` if the value is empty, `false` otherwise.
*/
declare function isEmpty(value: any): boolean;
/**
* Checks if a value is a string and a date.
* @param stringDate - The string to check.
* @returns Returns `true` if the string is a date, `false` otherwise.
*/
declare function isStringADate(stringDate: string): boolean;
/**
* Formats a date.
* @param format - The format of the date.
* @param date - The date to format.
* @returns The formatted date.
*/
declare function formatDate(format: any, date?: Date | StringDate): string | undefined;
/**
* Formats a date.
* @param format - The format of the date.
* @returns A function that formats a date.
*/
declare function dateFormatter(format: string): (date: Date | StringDate) => string | undefined;
/**
* Converts a date string to a date object.
* @param date - The date string to convert.
* @returns The date object.
*/
declare function YYYY_MM_DD_hh_mm_ss_ToUtcDate(dateYYYY_MM_DD_hh_mm_ss: string): number;
/**
* Converts a date object to an object.
* @param date - The date object to convert.
* @returns The date object.
*/
declare function dateToObj(date: Date | StringDate): {

@@ -368,11 +740,74 @@ YYYY: number;

} | undefined;
/**
* Converts a date object to a string.
* @param date - The date object to convert.
* @returns The date string.
*/
declare function diffInDaysYYYY_MM_DD(iniDate: Date | StringDate, endDate: Date | StringDate): number;
/**
* Adds days to a date.
* @param daysToSubtract - The number of days to add.
* @param date - The date to add days to.
* @returns The date with the added days.
*/
declare function addDays(daysToSubtract: number, date: Date | StringDate): Date;
/**
* Subtracts days from a date.
* @param daysToSubtract - The number of days to subtract.
* @param date - The date to subtract days from.
* @returns The date with the subtracted days.
*/
declare function subtractDays(daysToSubtract: number, date: Date | StringDate): Date;
/**
* Gets the day of the week.
* @param date - The date to get the day of the week.
* @returns The day of the week.
*/
declare function previousDayOfWeek(dayOfWeek: 0 | 1 | 2 | 3 | 4 | 5 | 6, date: Date | StringDate): Date;
/**
* Gets the same date or the previous Friday for weekends.
* @param date - The date to get the same date or the previous Friday.
* @returns The same date or the previous Friday.
*/
declare function getSameDateOrPreviousFridayForWeekends(date: Date | StringDate): Date;
/**
* Checks if a date is midnight.
* @param date - The date to check.
* @returns Returns `true` if the date is midnight, `false` otherwise.
*/
declare function isDateMidnight(date: Date):boolean | undefined;
/**
* Sets a date to midnight.
* @param date - The date to set to midnight.
* @returns The date set to midnight.
*/
declare function setDateToMidnight(date: Date | StringDate): Date;
/**
* Gets the date of the previous month.
* @param date - The date to get the previous month.
* @returns The date of the previous month.
*/
declare function replaceAll(str: any, ...fromTo: any[]): any;
/**
* Replaces all occurrences of a substring in a string.
* @param str - The string to replace the substring in.
* @param fromTo - The substring to replace and the new substring.
* @returns The string with the replaced substring.
*/
declare function cleanString(str: any): any;
/**
* Cleans a string by removing all non-alphanumeric characters.
* @param str - The string to clean.
* @returns The cleaned string.
*/
declare function repeat(numberOfTimes: any): {

@@ -383,2 +818,8 @@ times: (funToRepeat: any) => any[];

};
/**
* Repeats a function a specified number of times.
* @param numberOfTimes - The number of times to repeat the function.
* @returns An object with functions to repeat the function.
*/
declare function oneIn(period: any): {

@@ -390,4 +831,27 @@ calls: (runFunc: any) => {

};
/**
* Calls a function one in a specified period.
* @param period - The period to call the function.
* @returns An object with functions to call the function.
*/
declare function loopIndexGenerator(initValue: any, iterations: any): Generator<any, void, unknown>;
/**
* Retries a function with a sleep time between each retry.
* @template T The type of the parameters for the function to run.
* @param times The number of times to retry the function.
* @param updateSleepTimeFun A function that updates the sleep time between retries.
* @param funToRun The function to run.
* @param funToRunParams The parameters for the function to run.
* @param shouldStopRetrying A function that determines whether to stop retrying based on the result of the function.
* @returns A Promise that resolves with the result of the function.
*/
declare function retryWithSleep<T>(times: number, updateSleepTimeFun: (currentSleepTime?:number, index?:number)=>number, funToRun: (...params:T[])=>any, funToRunParams: T[]|undefined, shouldStopRetrying?: (result?:any)=>boolean): Promise<any>;
/**
* Processes the exit with the given error.
* @param error - The error object.
*/
declare function processExit(error: any): void;

@@ -710,2 +1174,2 @@

export { Chrono, CustomError, Enum, EnumMap, RE, RLog, Table, Text, Timeline, YYYY_MM_DD_hh_mm_ss_ToUtcDate, addDays, anonymize, arrayOfObjectsToObject, arraySorter, arrayToObject, bearerSanitizer, between, cleanString, cloneCopy, colorByStatus, colorMessage, colorMessageByStatus, colors, copyPropsWithValue, copyPropsWithValueUsingRules, createCustomErrorClass, dateFormatter, dateToObj, deepFreeze, diffInDaysYYYY_MM_DD, exclude, fetchImproved, ffletchMaker, fillWith, filterFlatMap, filterMap, findDeepKey, findSolution, firstCapital, fletch, formatDate, getAt, getSameDateOrPreviousFridayForWeekends, groupByWithCalc, indexOfNthMatch, innerRightJoinWith, isDate, isDateMidnight, isEmpty, isPromise, isStringADate, lengthSanitizer, log, logWithPrefix, loopIndexGenerator, mapWithNext, mapWithPrevious, matchByPropId, memoize, mergeArrayOfObjectsRenamingProps, notTo, oneIn, parallel, partialAtPos, pickPaths, pipe, pipeWhile, pipeWithChain, plan, previousDayOfWeek, processExit, project, promiseAll, promiseFunToFutureFun, pushAt, pushUniqueKey, pushUniqueKeyOrChange, queryObjToStr, removeDuplicates, repeat, replaceAll, retryWithSleep, runFunctionsSyncOrParallel, runFutureFunctionsInParallel, sanitize, setAt, setDateToMidnight, sleep, sleepWithFunction, sleepWithValue, something, sorterByPaths, splitCond, subtractDays, transition, traverse, traverseVertically, uncurry, unionWithHashKeys, unionWithHashKeysUnc, urlCompose, urlDecompose, varSubsDoubleBracket, wildcardToRegExp };
export { Chrono, CustomError, Enum, EnumMap, RE, RLog, Table, Text, Timeline, YYYY_MM_DD_hh_mm_ss_ToUtcDate, _delete, addDays, anonymize, arrayOfObjectsToObject, arraySorter, arrayToObject, bearerSanitizer, between, cleanString, cloneCopy, colorByStatus, colorMessage, colorMessageByStatus, colors, copyPropsWithValue, copyPropsWithValueUsingRules, createCustomErrorClass, dateFormatter, dateToObj, deepFreeze, diffInDaysYYYY_MM_DD, exclude, fetchImproved, ffletchMaker, fillWith, filterFlatMap, filterMap, findDeepKey, findSolution, firstCapital, fletch, formatDate, getAt, getSameDateOrPreviousFridayForWeekends, groupByWithCalc, indexOfNthMatch, innerRightJoinWith, isDate, isDateMidnight, isEmpty, isPromise, isStringADate, lengthSanitizer, log, logWithPrefix, loopIndexGenerator, mapWithNext, mapWithPrevious, matchByPropId, memoize, mergeArrayOfObjectsRenamingProps, notTo, oneIn, parallel, partialAtPos, pickPaths, pipe, pipeWhile, pipeWithChain, plan, previousDayOfWeek, processExit, project, promiseAll, promiseFunToFutureFun, pushAt, pushUniqueKey, pushUniqueKeyOrChange, queryObjToStr, removeDuplicates, repeat, replaceAll, retryWithSleep, runFunctionsSyncOrParallel, runFutureFunctionsInParallel, sanitize, setAt, setDateToMidnight, skip, sleep, sleepWithFunction, sleepWithValue, something, sorterByPaths, splitCond, stop, subtractDays, transition, traverse, traverseVertically, uncurry, unionWithHashKeys, unionWithHashKeysUnc, urlCompose, urlDecompose, varSubsDoubleBracket, wildcardToRegExp };

8

dist/cjs/jsUtils.js

@@ -553,3 +553,3 @@ 'use strict';

// let objTo = {a:{b:2},c:3}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}}}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}},l:5}
// copyPropsWithValueUsingRules(objTo, [{from:'a.b', to:'c'}, {from:'d.e.f', to:'d'}])(objFrom)

@@ -560,3 +560,3 @@ // objTo

// let objTo = {a:{b:2},c:3}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}}}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}}, l:5}
// copyPropsWithValueUsingRules(objTo,

@@ -573,4 +573,4 @@ // [

function copyPropsWithValue(objDest, shouldUpdateOnlyEmptyFields = false) {
return function (input) {
traverse(input, (nodeValue, currentPath) => {
return function (inputObj) {
traverse(inputObj, (nodeValue, currentPath) => {
if (isALeaf(nodeValue) === false)

@@ -577,0 +577,0 @@ return;

@@ -524,3 +524,3 @@ 'use strict';

// let objTo = {a:{b:2},c:3}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}}}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}},l:5}
// copyPropsWithValueUsingRules(objTo, [{from:'a.b', to:'c'}, {from:'d.e.f', to:'d'}])(objFrom)

@@ -531,3 +531,3 @@ // objTo

// let objTo = {a:{b:2},c:3}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}}}
// let objFrom = {a:{b:4},c:8,d:{e:{f:12}}, l:5}
// copyPropsWithValueUsingRules(objTo,

@@ -544,4 +544,4 @@ // [

function copyPropsWithValue(objDest, shouldUpdateOnlyEmptyFields = false) {
return function (input) {
traverse(input, (nodeValue, currentPath) => {
return function (inputObj) {
traverse(inputObj, (nodeValue, currentPath) => {
if (isALeaf(nodeValue) === false)

@@ -548,0 +548,0 @@ return;

@@ -10,9 +10,21 @@ /**

* Create event/s and start the timer.
* @param eventNames name of the event or array with events
* @param eventNames Name of the event or array with event names.
* @example
* // Single event
* chrono.time('step1');
*
* // Multiple events
* chrono.time(['step1', 'step2']);
*/
time(eventNames: string | string[]): void
time(eventNames: string | string[]): void;
/**
* Stop the timer for the envent/s.
* @param eventNames name of the event or array with events
* Stop the timer for the event/s.
* @param eventNames Name of the event or array with event names.
* @example
* // Single event
* chrono.timeEnd('step1');
*
* // Multiple events
* chrono.timeEnd(['step1', 'step2']);
*/

@@ -22,34 +34,3 @@ timeEnd(eventNames: string | string[]): void

/**
* console.log the following report below:
* ```
* chronoCreation : 2023-11-05T11:50:54.798Z
* report : 2023-11-05T11:50:56.119Z
*
* Timeline of events:
* ┌────────┬───────────────────────────────────────────────────────────────────────────────────────┐
* │ Events │ ms 0 656 1198 1300 │
* ├────────┼───────────────────────────────────────────────────────────────────────────────────────┤
* │ step1 │ |--------------------------------------| || │
* │ step2 │ |------------------------------------| │
* │ step3 │ |-----------------------------| │
* └────────┴───────────────────────────────────────────────────────────────────────────────────────┘
*
* Total elapse Time of each event:
* ┌───────┬────────┬────────────┐
* │ name │ elapse │ percentage │
* ├───────┼────────┼────────────┤
* │ step1 │ 655 │ 36.85 │
* │ step2 │ 620 │ 34.86 │
* │ step3 │ 503 │ 28.29 │
* └───────┴────────┴────────────┘
*
* Coinciding Events timeline:
* ┌───────────────┬──────────┬────────────┐
* │ runningEvents │ elapseMs │ percentage │
* ├───────────────┼──────────┼────────────┤
* │ step1 │ 655 │ 51.39 │
* │ step2 │ 116 │ 9.16 │
* │ step2,step3 │ 503 │ 39.45 │
* └───────────────┴──────────┴────────────┘
* ```
* Print the report of the events in the console.
*/

@@ -59,5 +40,14 @@ report(): void

/**
* This is an implementation of Chrono().time() to use in pipeline of functions. Prepaire the time event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes data is passed to the next function. This function
* This is an implementation of Chrono().time() to use in a pipeline of functions. Prepare the time event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes, data is passed to the next function. This function
* takes the input and passes it to the next function without modifications.
* @param event Name of the event or array with event names.
* @returns A function that takes the input data and passes it to the next function without modifications.
* @example
* const pipeline = [
* chrono.setTime('step1'),
* // other functions in the pipeline
* ];
*
* const result = pipeline.reduce((data, fn) => fn(data), inputData);
*/

@@ -67,5 +57,14 @@ setTime: (event: string | string[]) => <T>(data: T) => T;

/**
* This is an implementation of Chrono().timeEnd() to use in pipeline of functions. Prepaire the timeEnd event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes data is passed to the next function. This function
* This is an implementation of Chrono().timeEnd() to use in a pipeline of functions. Prepare the timeEnd event function that will be
* triggered in the execution of the pipeline. As this is for logging purposes, data is passed to the next function. This function
* takes the input and passes it to the next function without modifications.
* @param event Name of the event or array with event names.
* @returns A function that takes the input data and passes it to the next function without modifications.
* @example
* const pipeline = [
* // other functions in the pipeline
* chrono.setTimeEnd('step1'),
* ];
*
* const result = pipeline.reduce((data, fn) => fn(data), inputData);
*/

@@ -75,10 +74,36 @@ setTimeEnd: (event: string | string[]) => <T>(data: T) => T;

/**
* This is an implementation of Chrono().report() to use in pipeline of functions. Its execution will log the event reports as in
* This is an implementation of Chrono().report() to use in a pipeline of functions. Its execution will log the event reports as in
* Chrono().report() and returns the same data received as input.
* @returns A function that takes the input data, logs the event reports, and returns the same data.
* @example
* const pipeline = [
* // other functions in the pipeline
* chrono.logReport,
* ];
*
* const result = pipeline.reduce((data, fn) => fn(data), inputData);
*/
logReport: <T>(data: T) => T;
/**
* Get the current state of the Chrono timer.
* @returns The current state of the Chrono timer.
*/
getChronoState: () => {};
/**
* Set the Chrono timer state using the Performance API format.
* @param performanceGetEntriesByTypeOjb The Performance API object returned by `performance.getEntriesByType('measure')`.
*/
setChronoStateUsingPerformanceAPIFormat: (performanceGetEntriesByTypeOjb: any) => void;
/**
* Get the Chrono timer state using the Performance API format.
* @returns The Chrono timer state in the Performance API format.
*/
getChronoStateUsingPerformanceAPIFormat: () => any[];
/**
* Calculate the average time for each event.
*/
average: () => void;

@@ -85,0 +110,0 @@ }

@@ -1,122 +0,77 @@

export default jsUtils;
declare namespace jsUtils {
export { logWithPrefix };
export { firstCapital };
export { varSubsDoubleBracket };
export { queryObjToStr };
export { CustomError };
export { createCustomErrorClass }
export { urlCompose };
export { urlDecompose };
export { indexOfNthMatch };
export { colors };
export { colorMessage };
export { colorMessageByStatus };
export { colorByStatus };
export { findDeepKey };
export { deepFreeze };
export { getAt };
export { setAt };
export { sorterByPaths };
export { filterFlatMap };
export { arraySorter };
export { isPromise };
export { sleep };
export { sleepWithValue };
export { sleepWithFunction };
export { notTo };
export { arrayToObject };
export { arrayOfObjectsToObject };
export { removeDuplicates };
export { traverse };
export { copyPropsWithValue };
export { copyPropsWithValueUsingRules };
export { EnumMap };
export { Enum };
export { transition };
export { pushUniqueKey };
export { pushUniqueKeyOrChange };
export { pushAt };
export { memoize };
export { fillWith };
export { isDate };
export { isEmpty };
export { isStringADate };
export { formatDate };
export { dateFormatter };
export { YYYY_MM_DD_hh_mm_ss_ToUtcDate };
export { dateToObj };
export { diffInDaysYYYY_MM_DD };
export { addDays };
export { subtractDays };
export { previousDayOfWeek };
export { getSameDateOrPreviousFridayForWeekends };
export { replaceAll };
export { cleanString };
export { repeat };
export { oneIn };
export { loopIndexGenerator };
export { retryWithSleep };
export { processExit };
}
/**
* @fileoverview TypeScript declarations for jsUtils module.
* @module jsUtils
*/
/**
* Utility functions for JavaScript.
* @namespace jsUtils
*/
/**
* Logs a message with a prefix.
* @param {any} title - The prefix for the log message.
* @param {any} displayFunc - The function to display the log message.
* @returns {Function} - The log function.
*/
export function logWithPrefix(title: any, displayFunc: any): (message: any) => any;
/**
* Capitalizes the first letter of a string.
* @param {any} str - The string to capitalize.
* @returns {any} - The capitalized string.
*/
export function firstCapital(str: any): any;
/**
* String template funcionality. Given a string with "text {{var1}} text2 {{var2}}""
* and an state object {var1: 'fool', var2: 'bar'}. It returns a string substituting
* the template variables for its value. "text fool text2 bar""
* state can be a string, an object or an array.
* For mode=url a state array is converted into a list of values separated by comma.
* For mode=url a state object is converted into query field=value separated by &
* If mode is different to url. state is stringigify.
* @example
* ```
* varSubsDoubleBracket(`
* {
* "id": 1231,
* "description": "{{description=\"This is a test\"}}",
* "car": "{{plate}}",
* }`, {plate:{a:3}}) //?
* ```
* This will produce
* ```
* `{
* "id": 1231,
* "description": "{{description=\"This is a test\"}}",
* "car": {a:3},
* }`
* ```
* varSubsDoubleBracket('https://bank.account?account={{account}}', {account:['10232-1232','2331-1233']},'url')
* https://bank.account?account=10232-1232,2331-1233
*
* varSubsDoubleBracket('https://bank.account?{{params}}', {params:{a:'10232-1232',b:'2331-1233'}},'url')
* https://bank.account?a=10232-1232&b=2331-1233}
*
* @param strToResolveVars string with variables to be substituted. The string can represent a Json or url.
* @param state state with the values to substitute the template vars.
* @param mode: url: for converting state arrays into separated comma field=value1,value2
* and objects into field=value & field2=value2. if mode is not specified: state is stringify.
* @returns string after substituting the template vars for its corresponding values from state object.
* String template functionality. Given a string with "text {{var1}} text2 {{var2}}"
* and a state object {var1: 'foo', var2: 'bar'}, it returns a string substituting
* the template variables for their values. "text foo text2 bar"
* The state can be a string, an object, or an array.
* For mode=url, a state array is converted into a list of values separated by commas.
* For mode=url, a state object is converted into query field=value separated by '&'.
* If mode is different from 'url', the state is stringified.
* @param {string} strToResolveVars - The string with variables to be substituted. The string can represent a JSON or URL.
* @param {any} state - The state with the values to substitute the template variables.
* @param {string} [mode] - The mode for converting the state. 'url' for converting state arrays into comma-separated field=value1,value2
* and objects into field=value & field2=value2. If mode is not specified, the state is stringified.
* @returns {string} - The string after substituting the template variables for their corresponding values from the state object.
*/
export function varSubsDoubleBracket(strToResolveVars: string, state: any, mode?: 'url'): string;
/**
* Converts a query object to a string representation.
* @param {any} query - The query object to convert.
* @returns {string} - The string representation of the query object.
*/
export function queryObjToStr(query: any): string;
/**
* Custom error class that extends the Error class.
* @extends Error
*/
export class CustomError extends Error {
constructor(name?: string, message?: string, data?: {
status: number;
});
data: {
status: number;
};
/**
* Creates an instance of CustomError.
* @param {string} [name='GENERIC'] - The name of the error.
* @param {string} message - The message of the error.
* @param {object} [data={ status: 500 }] - Additional data about the error.
*/
constructor(name?: string, message?: string, data?: { status: number });
data: { status: number };
}
/**
* Creates a custom error class with the given error name.
* @param {string} errorName - The name of the custom error class.
* @returns {object} - The custom error class.
*/
export function createCustomErrorClass(errorName: string): {
new (name?: string, message?: string, data?: { status: number}): {
name: string;
data: {
status: number;
};
map(func: Function): any;
chain(func: Function): any;
message: string;
stack?: string;
new (name?: string, message?: string, data?: { status: number }): {
name: string;
data: { status: number };
map(func: Function): any;
chain(func: Function): any;
message: string;
stack?: string;
};

@@ -128,2 +83,10 @@ of: typeof CustomError;

};
/**
* Composes a URL from the gateway URL, service name, and service path.
* @param {any} gatewayUrl - The gateway URL.
* @param {any} serviceName - The service name.
* @param {any} servicePath - The service path.
* @returns {object} - The composed URL object.
*/
export function urlCompose(gatewayUrl: any, serviceName: any, servicePath: any): {

@@ -135,4 +98,24 @@ gatewayUrl: any;

};
/**
* Decomposes a URL into the gateway URL, service name, and service path.
* @param {any} url - The URL to decompose.
* @param {any} listOfServiceNames - The list of service names.
* @returns {any} - The decomposed URL object.
*/
export function urlDecompose(url: any, listOfServiceNames: any): any;
/**
* Returns the index of the nth match of a substring in a string.
* @param {any} string - The string to search in.
* @param {any} toMatch - The substring to match.
* @param {any} nth - The nth match to find.
* @returns {any} - The index of the nth match.
*/
export function indexOfNthMatch(string: any, toMatch: any, nth: any): any;
/**
* Namespace for color constants.
* @namespace colors
*/
export namespace colors {

@@ -168,101 +151,290 @@ const red: string;

}
/**
* Colors a message with the specified color.
* @param {any} message - The message to color.
* @param {any} color - The color to apply.
* @returns {string} - The colored message.
*/
export function colorMessage(message: any, color: any): string;
/**
* Colors a message based on the status.
* @param {any} message - The message to color.
* @param {any} status - The status to determine the color.
* @returns {string} - The colored message.
*/
export function colorMessageByStatus(message: any, status: any): string;
/**
* Gets the color based on the status.
* @param {any} status - The status to determine the color.
* @returns {string} - The color.
*/
export function colorByStatus(status: any): string;
/**
* Finds the deep key in an object.
* @param {any} objIni - The initial object.
* @param {any} keyToFind - The key to find.
* @returns {any[]} - The array of found keys.
*/
export function findDeepKey(objIni: any, keyToFind: any): any[];
/**
* Freezes an object deeply.
* @param {any} o - The object to freeze.
* @returns {any} - The frozen object.
*/
export function deepFreeze(o: any): any;
/**
* Gets the value at the specified path in an object.
* @param {any} obj - The object to get the value from.
* @param {any} valuePath - The path to the value.
* @returns {any} - The value at the specified path.
*/
export function getAt(obj: any, valuePath: any): any;
/**
* Sets the value at the specified path in an object.
* @param {any} obj - The object to set the value in.
* @param {any} valuePath - The path to the value.
* @param {any} value - The value to set.
* @returns {string} - The result of setting the value.
*/
export function setAt(obj: any, valuePath: any, value: any): string;
/**
* Creates a sorter function to use as a parameter in array.prototype.sort(sorter).
* It can order by several fields. If fields are equal, it will uneven using subsequent fields.
* @param {any} paths - List of paths to sort by. One path for each field to order by. Route path is of the shape 'person.details.age'. If it is only one field, it can be a string.
* @param {boolean} [isAsc=true] - Optional. Default: true. true: to order ascending. false: to order descending.
* @returns {Function} - A sorter function to include in array.prototype.sort(sorter).
*/
export function sorterByPaths(paths: any, isAsc?: boolean): (objA: any, objB: any) => number;
/**
* Create a sorter function to use as a parameter in array.prototype.sort(sorter):
* It can order by several fields. If fields are equal it will uneven using
* subsequent fields.
* @param paths List of paths to sort by. One path for each field to order by. Route path is
* of the shape. ex: 'person.details.age'. If it is only one field it can be a string.
* @param isAsc Optional. Default: true. true: to order ascending. false: to order descending
* @returns Return a sorter function to include in array.prototype.sort(sorter)
* Filters and maps an array.
* @param {any} mapWithUndefinedFilterFun - The array to filter and map.
* @param {any} data - The data to filter and map.
* @returns {any[]} - The filtered and mapped array.
*/
export function sorterByPaths(paths: any, isAsc?: boolean): (objA: any, objB: any) => number;
export function filterFlatMap(mapWithUndefinedFilterFun: any, data: any): any[];
/**
* Sorts an array in ascending or descending order.
* @param {boolean} [isAsc=true] - Optional. Default: true. true: to order ascending. false: to order descending.
* @returns {Function} - A sorter function to use with array.prototype.sort(sorter).
*/
export function arraySorter(isAsc?: boolean): (a: any, b: any) => 1 | -1 | 0;
/**
* Checks if an object is a Promise.
* @param {any} obj - The object to check.
* @returns {boolean} - true if the object is a Promise, false otherwise.
*/
export function isPromise(obj: any): boolean;
export function sleep(ms: any): Promise<any>;
export function sleepWithValue(ms: any, value: any): Promise<any>;
export function sleepWithFunction(ms: any, func: any, ...params: any[]): Promise<any>;
export function notTo(funct: any): (...params: any[]) => boolean;
export function arrayToObject(arr: any, defaultValueFunction: any): any;
/**
* Sleeps for the specified number of milliseconds.
* @param {number} ms - The number of milliseconds to sleep.
* @returns {Promise<any>} - A Promise that resolves after the specified number of milliseconds.
*/
export function sleep(ms: number): Promise<any>;
/**
* Sleeps for the specified number of milliseconds and resolves with the specified value.
* @param {number} ms - The number of milliseconds to sleep.
* @param {any} value - The value to resolve with.
* @returns {Promise<any>} - A Promise that resolves after the specified number of milliseconds with the specified value.
*/
export function sleepWithValue(ms: number, value: any): Promise<any>;
/**
* Sleeps for the specified number of milliseconds and executes the specified function with the specified parameters.
* @param {number} ms - The number of milliseconds to sleep.
* @param {Function} func - The function to execute.
* @param {...any} params - The parameters to pass to the function.
* @returns {Promise<any>} - A Promise that resolves after the specified number of milliseconds with the result of the function.
*/
export function sleepWithFunction(ms: number, func: Function, ...params: any[]): Promise<any>;
/**
* Negates a function.
* @param {Function} funct - The function to negate.
* @returns {Function} - The negated function.
*/
export function notTo(funct: Function): (...params: any[]) => boolean;
/**
* Converts an array to an object using the specified default value function.
* @param {any} arr - The array to convert.
* @param {Function} defaultValueFunction - The function to generate the default value.
* @returns {any} - The converted object.
*/
export function arrayToObject(arr: any, defaultValueFunction: Function): any;
/**
* Converts an array of objects to an object.
* @param {any} iterable - The array of objects to convert.
* @returns {any} - The converted object.
*/
export function arrayOfObjectsToObject(iterable: any): any;
/**
* Removes duplicates from an array.
* @param {any} arr - The array to remove duplicates from.
* @returns {any[]} - The array without duplicates.
*/
export function removeDuplicates(arr: any): any[];
/**
* Traverses an object and applies a reviver function to each node.
* @param {any} objIni - The object to traverse.
* @param {Function} reviver - The function to be called for each node.
* @param {boolean} [pureFunction] - true: work with a deep clone of objIni, false: work with objIni passed as a parameter.
* @returns {any} - The object after applying the reviver actions.
*/
export function traverse(objIni: any, reviver: (value: any, path: string[], parent: any, prop: string) => any, pureFunction?: boolean): any;
/**
* Access each node of the object calling the reviver function. Reviver can return:
* undefined: no change
* traverse.skip: stop accessing subtrees
* traverse.stop: stop completly the object traverse
* traverse.delete: delete the current node
* traverse.match(stringQuery, reviverPath) return true if reviverPath match query string
*
* @param objIni The object to traverse.
* @param reviver The function to be called for each node
* @pureFunction true: work with a deepClone of objIni, false: work with objIni passed as a parameter.
* @returns Return the object after applying reviver actions
* Symbol to skip traversing a subtree.
* @type {symbol}
*/
export function traverse(objIni: any, reviver: (value: any, path: string[], parent: any, prop: string) => any, pureFunction?: boolean): any
export namespace traverse {
export const skip: symbol;
export const stop: symbol;
const _delete: symbol;
export { _delete as delete };
}
export const skip: symbol;
/**
* Takes vertifical slices of a two nested array and calls functionToRun with each slice
* Symbol to stop traversing the object.
* @type {symbol}
*/
export const stop: symbol;
/**
* Symbol to delete the current node.
* @type {symbol}
*/
export const _delete: symbol;
/**
* Takes vertical slices of a two-nested array and calls a function with each slice.
* @param {Function} functionToRun - The function to run with each vertical slice.
* @param {string[]} verFields - The fields inside each item of the traverse array that contains the second nested arrays to iterate vertically.
* @param {any[]} toTraverse - The array to traverse.
* @returns {void}
*/
export function traverseVertically(functionToRun: (verticalSlice: object, runIndex: number) => any, verFields: string[], toTraverse: any[]): void;
/**
* Projects a subset of a JSON object based on specified paths, optionally removing properties marked for deletion.
*
* @param {string[]} paths - An array of strings representing the paths to the properties in the JSON object that should be included in the output.
* @param {Object} json - The JSON object from which the properties specified by paths will be extracted.
* @param {boolean} [removeWithDelete=true] - A boolean indicating whether properties in the JSON object marked with a specific delete flag should be removed from the output. Defaults to true, meaning properties marked for deletion will be removed.
*
* @returns {Object} A new JSON object containing only the properties specified by the paths array. If removeWithDelete is true, any properties marked for deletion will not be included in the returned object.
*
* @example
* ```
* traverseVertically (
* functionToRun
* ['marathonResults'], // List of fields for the second level nested array
* [{name:'Jose',marathonResults:[12,35]},{name:'Ana',marathonResults:[1]}]
* )
* ```
* This will produce folllowing calls
* ```
* functionToRun([{name:'Jose', marathonResults:12}, {name:'Ana',marathonResults:1}])
* functionToRun([{name:'Jose', marathonResults:35}, {name:'Ana',marathonResults:undefined}])
* ```
*
* @param functionToRun This function will be called for each vertical slice.
* @param verFields Fields inside each item of the traverse array that contains the second nested arrays to iterate vertically.
* @param toTraverse: Array to be traverse
* @returns void
* // Assuming a JSON object `data` as follows:
* // {
* // user: {
* // name: "John Doe",
* // age: 30,
* // email: "johndoe@example.com",
* // _delete: { email: true }
* // }
* // }
* // And calling the function with paths to include the user's name and email:
* project(['user.name', 'user.email'], data);
* // Returns: { user: { name: "John Doe" } }
* // Note: The email property is not included in the output because it's marked for deletion.
*/
export function traverseVertically(functionToRun: (verticalSlice: object, runIndex: number) => any, verFields: string[], toTraverse: any[]): void
export function project(paths: string[], json: any): any
/**
* Totally recreate a new object with the selected values using jsonpath-plus format for queries.
* Given objDest and shouldUpdateOnlyEmptyFields generates function that expect inputObj to copy all properties from inputObj to objDest.
*
* @param paths Array with the queries for the projection. First char must be + to include or - to remove
* @param json Subject object to project.
* @param {Object} objDest Destination object for the copy.
* @param {boolean} shouldUpdateOnlyEmptyFields? true: does not replace destination fields with values.
* @example
* // returns {a:{b:{c:3,e:9}}}
* project(['+$.a.b','-$.a.b.d'], {a:{b:{c:3,d:5,e:9}}});
* @returns any
* // returns {isin:123456, name:'test'}
* copyPropsWithValue({isin:123456}, true)({isin:123, name:'test'});
* // returns {isin:123, name:'test'}
* copyPropsWithValue({isin:123456}, false)({isin:123, name:'test'});
* @returns {Function} A function that takes an input object for props to be copied in objDest.
*/
export function project(paths:string[], json:any):any
export function copyPropsWithValue(objDest: any, shouldUpdateOnlyEmptyFields?: boolean): (input: any) => any;
export function copyPropsWithValue(objDest: any, shouldUpdateOnlyEmptyFields?: boolean): (inputObj: any) => any;
/**
* Given objDest, copyRules and shouldUpdateOnlyEmptyFields generates function that expect input object to copy only properties indicated by copyRules from inputObj to objDest.
*
* @param {Object} objDest - The destination object to copy properties into.
* @param {Array<string|Object>} copyRules - An array of rules specifying which properties to copy.
* Each rule can be either a string (for same-named properties) or an object with 'from' and 'to' keys.
* @param {boolean} [shouldUpdateOnlyEmptyFields=false] - If true, only update fields in the destination object that are empty.
* @returns {Function} A function that takes an input object for props to be copied in objDest.
*
* @example
* let objTo = {a:{b:2},c:3};
* let objFrom = {a:{b:4},c:8,d:{e:{f:12}}};
* copyPropsWithValueUsingRules(objTo, [{from:'a.b', to:'c'}, {from:'d.e.f', to:'d'}])(objFrom);
* // objTo is now {a:{b:2},c:4,d:12}
*
* @example
* let objTo = {a:{b:2},c:3};
* let objFrom = {a:{b:4},c:8,d:{e:{f:12}}};
* copyPropsWithValueUsingRules(objTo, [{from:'a.b', to:'c'}, {from:'d.e.f', to:'d.f'}, {from:'d.e.g', to:'d.g'}], true)(objFrom);
* // objTo is now {a:{b:2},c:3,d:{f:12}}
*/
export function copyPropsWithValueUsingRules(objDest: any, copyRules: any, shouldUpdateOnlyEmptyFields?: boolean): (inputObj: any) => any;
export class EnumMap {
/**
* Creates an instance of EnumMap.
* @param {object} values - The values of the enum.
*/
constructor(values: any);
/**
* A Proxy handler method for getting a property value.
*/
get(target: any, prop: any): any;
/**
* A Proxy handler method for setting a property value.
*/
set(_undefined: any, prop: any): void;
/**
* Gets the current active value of the enum.
* @returns {string} The active enum value.
*/
invert(): EnumMap;
}
export class Enum {
constructor(values: any, rules: any);
/**
* Creates an instance of Enum.
* @param {Array<string>} values - The values of the enum.
* @param {object} rules - The rules defining valid transitions between enum values.
*/
constructor(values: Array<string>, rules: object);
/**
* A Proxy handler method for getting a property value.
*/
get: (_target: any, prop: any) => any;
/**
* A Proxy handler method for setting a property value.
*/
set: (_undefined: any, prop: any, value: any) => boolean;
getValue: () => any;
/**
* Gets the current active value of the enum.
* @returns {string} The active enum value.
*/
getValue: () => string;
}
/**
* Creates a state machine transition function.
* @param {object} states - The states of the state machine.
* @param {object} events - The events of the state machine.
* @param {object} transitions - The transitions of the state machine.
* @returns {Function} A function that transitions the state machine.
*/
export function transition(states: any, events: any, transitions: any): {

@@ -272,5 +444,64 @@ (event: any): any;

};
export function pushUniqueKey(row: any, table: any, indexes?: number[]): any;
/**
* Pushes a unique key into a table.
* @param row
* @param table
* @param indexes
* @returns
* @example
* ```
* pushUniqueKey({id: 1, name: 'John'}, [{id: 1, name: 'John'}], [0]) //?
* ```
* This will produce
* ```
* [{id: 1, name: 'John'}]
* ```
*/
export function pushUniqueKey(row: any, table: any[], indexes?: number[]): any;
/**
* Pushes a unique key into a table or changes the existing row.
* @param newRow
* @param table
* @param indexes
* @param mergeFun
* @returns
* @example
* ```
* pushUniqueKeyOrChange({id: 1, name: 'John'}, [{id: 1, name: 'John'}], [0], (oldRow, newRow) => ({...oldRow, ...newRow})) //?
* ```
* This will produce
* ```
* [{id: 1, name: 'John'}]
* ```
*/
export function pushUniqueKeyOrChange(newRow: any, table: any, indexes: number[], mergeFun: any): any;
/**
* Pushes a value at a given position in an array.
* @param pos
* @param value
* @param arr
* @returns
* @example
* ```
* pushAt(1, 'a', ['b', 'c']) //?
* ```
* This will produce
* ```
* ['b', 'a', 'c']
* ```
*/
export function pushAt(pos: any, value: any, arr: any): any;
/**
* Memoizes a function.
* @returns
* @example
* ```
* const memoizeMap = memoize().memoizeMap;
* const memoizeWithHashFun = memoize().memoizeWithHashFun;
* ```
*/
export function memoize(): {

@@ -280,2 +511,17 @@ memoizeMap: (func: any, ...params: any[]) => any;

};
/**
* Fills an array with a given value.
* @param mapper
* @param lenOrWhileTruthFun
* @returns
* @example
* ```
* fillWith('a', 3) //?
* ```
* This will produce
* ```
* ['a', 'a', 'a']
* ```
*/
export function fillWith(mapper: any, lenOrWhileTruthFun: any): any[];

@@ -288,8 +534,48 @@

export function isDate(d: any): boolean;
/**
* Checks if a value is empty: undefined, null, '', 0, NaN, [], {}
* empty is bigger than falsy as we have added [] and {} that are truthy
* @param value - The value to check.
* @returns Returns `true` if the value is empty, `false` otherwise.
*/
export function isEmpty(value: any): boolean;
/**
* Checks if a value is a string and a date.
* @param stringDate - The string to check.
* @returns Returns `true` if the string is a date, `false` otherwise.
*/
export function isStringADate(stringDate: string): boolean;
/**
* Formats a date.
* @param format - The format of the date.
* @param date - The date to format.
* @returns The formatted date.
*/
export function formatDate(format: any, date?: Date | StringDate): string | undefined;
/**
* Formats a date.
* @param format - The format of the date.
* @returns A function that formats a date.
*/
export function dateFormatter(format: string): (date: Date | StringDate) => string | undefined;
/**
* Converts a date string to a date object.
* @param date - The date string to convert.
* @returns The date object.
*/
export function YYYY_MM_DD_hh_mm_ss_ToUtcDate(dateYYYY_MM_DD_hh_mm_ss: string): number;
/**
* Converts a date object to an object.
* @param date - The date object to convert.
* @returns The date object.
*/
export function dateToObj(date: Date | StringDate): {

@@ -304,11 +590,74 @@ YYYY: number;

} | undefined;
/**
* Converts a date object to a string.
* @param date - The date object to convert.
* @returns The date string.
*/
export function diffInDaysYYYY_MM_DD(iniDate: Date | StringDate, endDate: Date | StringDate): number;
/**
* Adds days to a date.
* @param daysToSubtract - The number of days to add.
* @param date - The date to add days to.
* @returns The date with the added days.
*/
export function addDays(daysToSubtract: number, date: Date | StringDate): Date;
/**
* Subtracts days from a date.
* @param daysToSubtract - The number of days to subtract.
* @param date - The date to subtract days from.
* @returns The date with the subtracted days.
*/
export function subtractDays(daysToSubtract: number, date: Date | StringDate): Date;
/**
* Gets the day of the week.
* @param date - The date to get the day of the week.
* @returns The day of the week.
*/
export function previousDayOfWeek(dayOfWeek: 0 | 1 | 2 | 3 | 4 | 5 | 6, date: Date | StringDate): Date;
/**
* Gets the same date or the previous Friday for weekends.
* @param date - The date to get the same date or the previous Friday.
* @returns The same date or the previous Friday.
*/
export function getSameDateOrPreviousFridayForWeekends(date: Date | StringDate): Date;
/**
* Checks if a date is midnight.
* @param date - The date to check.
* @returns Returns `true` if the date is midnight, `false` otherwise.
*/
export function isDateMidnight(date: Date):boolean | undefined;
/**
* Sets a date to midnight.
* @param date - The date to set to midnight.
* @returns The date set to midnight.
*/
export function setDateToMidnight(date: Date | StringDate): Date;
/**
* Gets the date of the previous month.
* @param date - The date to get the previous month.
* @returns The date of the previous month.
*/
export function replaceAll(str: any, ...fromTo: any[]): any;
/**
* Replaces all occurrences of a substring in a string.
* @param str - The string to replace the substring in.
* @param fromTo - The substring to replace and the new substring.
* @returns The string with the replaced substring.
*/
export function cleanString(str: any): any;
/**
* Cleans a string by removing all non-alphanumeric characters.
* @param str - The string to clean.
* @returns The cleaned string.
*/
export function repeat(numberOfTimes: any): {

@@ -319,2 +668,8 @@ times: (funToRepeat: any) => any[];

};
/**
* Repeats a function a specified number of times.
* @param numberOfTimes - The number of times to repeat the function.
* @returns An object with functions to repeat the function.
*/
export function oneIn(period: any): {

@@ -326,5 +681,28 @@ calls: (runFunc: any) => {

};
/**
* Calls a function one in a specified period.
* @param period - The period to call the function.
* @returns An object with functions to call the function.
*/
export function loopIndexGenerator(initValue: any, iterations: any): Generator<any, void, unknown>;
/**
* Retries a function with a sleep time between each retry.
* @template T The type of the parameters for the function to run.
* @param times The number of times to retry the function.
* @param updateSleepTimeFun A function that updates the sleep time between retries.
* @param funToRun The function to run.
* @param funToRunParams The parameters for the function to run.
* @param shouldStopRetrying A function that determines whether to stop retrying based on the result of the function.
* @returns A Promise that resolves with the result of the function.
*/
export function retryWithSleep<T>(times: number, updateSleepTimeFun: (currentSleepTime?:number, index?:number)=>number, funToRun: (...params:T[])=>any, funToRunParams: T[]|undefined, shouldStopRetrying?: (result?:any)=>boolean): Promise<any>;
/**
* Processes the exit with the given error.
* @param error - The error object.
*/
export function processExit(error: any): void;
//# sourceMappingURL=jsUtils.d.ts.map
{
"name": "js-awe",
"version": "1.0.67",
"version": "1.0.68",
"homepage": "https://github.com/josuamanuel/js-awe",

@@ -5,0 +5,0 @@ "author": "josuamanuel@hotmail.com",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc