Socket
Socket
Sign inDemoInstall

data-structure-typed

Package Overview
Dependencies
Maintainers
1
Versions
201
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

data-structure-typed - npm Package Compare versions

Comparing version 1.15.0 to 1.15.1

49

dist/utils/types/utils.d.ts

@@ -1,53 +0,4 @@

export type JSONSerializable = {
[key: string]: any;
};
export type JSONValue = string | number | boolean | undefined | JSONObject;
export interface JSONObject {
[key: string]: JSONValue;
}
export type AnyFunction<A extends any[] = any[], R = any> = (...args: A) => R;
export type Primitive = number | string | boolean | symbol | undefined | null | void | AnyFunction | Date;
export type Cast<T, TComplex> = {
[M in keyof TComplex]: T;
};
export type DeepLeavesWrap<T, TComplex> = T extends string ? Cast<string, TComplex> : T extends number ? Cast<number, TComplex> : T extends boolean ? Cast<boolean, TComplex> : T extends undefined ? Cast<undefined, TComplex> : T extends null ? Cast<null, TComplex> : T extends void ? Cast<void, TComplex> : T extends symbol ? Cast<symbol, TComplex> : T extends AnyFunction ? Cast<AnyFunction, TComplex> : T extends Date ? Cast<Date, TComplex> : {
[K in keyof T]: T[K] extends (infer U)[] ? DeepLeavesWrap<U, TComplex>[] : DeepLeavesWrap<T[K], TComplex>;
};
export type TypeName<T> = T extends string ? 'string' : T extends number ? 'number' : T extends boolean ? 'boolean' : T extends undefined ? 'undefined' : T extends AnyFunction ? 'function' : 'object';
export type JsonKeys<T> = keyof {
[P in keyof T]: number;
};
/**
* A function that emits a side effect and does not return anything.
*/
export type Procedure = (...args: any[]) => void;
export type DebounceOptions = {
isImmediate?: boolean;
maxWait?: number;
};
export interface DebouncedFunction<F extends Procedure> {
cancel: () => void;
(this: ThisParameterType<F>, ...args: [...Parameters<F>]): void;
}
export type MonthKey = 'January' | 'February' | 'March' | 'April' | 'May' | 'June' | 'July' | 'August' | 'September' | 'October' | 'November' | 'December';
export type Month = {
[key in MonthKey]: string;
};
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
export declare class TreeNode<T> {
id: string;
name?: string | undefined;
value?: T | undefined;
children?: TreeNode<T>[] | undefined;
constructor(id: string, name?: string, value?: T, children?: TreeNode<T>[]);
addChildren(children: TreeNode<T> | TreeNode<T>[]): void;
getHeight(): number;
}
export type OrderType = 'InOrder' | 'PreOrder' | 'PostOrder';
export type DeepProxy<T> = T extends (...args: any[]) => infer R ? (...args: [...Parameters<T>]) => DeepProxy<R> : T extends object ? {
[K in keyof T]: DeepProxy<T[K]>;
} : T;
export type DeepProxyOnChange = (target: any, property: string | symbol, value: any, receiver: any, descriptor: any, result: any) => void;
export type DeepProxyOnGet = (target: any, property: string | symbol, value: any, receiver: any, descriptor: any, result: any) => void;
export type CurryFunc<T> = T extends (...args: infer Args) => infer R ? Args extends [infer Arg, ...infer RestArgs] ? (arg: Arg) => CurryFunc<(...args: RestArgs) => R> : R : T;
export type ToThunkFn = () => ReturnType<TrlFn>;

@@ -54,0 +5,0 @@ export type Thunk = () => ReturnType<ToThunkFn> & {

66

dist/utils/types/utils.js
"use strict";
// export type JSONSerializable = {
// [key: string]: any
// }
Object.defineProperty(exports, "__esModule", { value: true });
exports.TreeNode = void 0;
var arr = ['1', 2, 4, 5, 6];
var a = 2;
var TreeNode = /** @class */ (function () {
function TreeNode(id, name, value, children) {
this.id = id;
this.name = name || '';
this.value = value || undefined;
this.children = children || [];
}
// TODO get set
// get name (): string | undefined {
// return this.name;
// }
//
// set name (name: string | undefined) {
// this.name = name;
// }
TreeNode.prototype.addChildren = function (children) {
if (!this.children) {
this.children = [];
}
if (children instanceof TreeNode) {
this.children.push(children);
}
else {
this.children = this.children.concat(children);
}
};
TreeNode.prototype.getHeight = function () {
// eslint-disable-next-line @typescript-eslint/no-this-alias
var beginRoot = this;
var maxDepth = 1;
if (beginRoot) {
var bfs_1 = function (node, level) {
if (level > maxDepth) {
maxDepth = level;
}
var children = node.children;
if (children) {
for (var i = 0, len = children.length; i < len; i++) {
bfs_1(children[i], level + 1);
}
}
};
bfs_1(beginRoot, 1);
}
return maxDepth;
};
return TreeNode;
}());
exports.TreeNode = TreeNode;
// export type CaseType =
// 'camel'
// | 'snake'
// | 'pascal'
// | 'constant'
// | 'kebab'
// | 'lower'
// | 'title'
// | 'sentence'
// | 'path'
// | 'dot';

@@ -1,99 +0,3 @@

import type { AnyFunction, JSONObject, JSONSerializable } from './types';
export declare function randomText(length: number): string;
export declare const uuidV4: () => string;
export declare class IncrementId {
private _id;
private readonly _prefix;
constructor(prefix?: string);
getId(): string;
}
export declare function incrementId(prefix?: string): () => string;
export declare const getValue: <T, K extends keyof T>(obj: T, names: K[]) => T[K][];
export declare const isObject: (object: string | JSONObject | boolean | AnyFunction | number) => boolean;
export declare const looseEqual: (a: any, b: any) => boolean;
export declare const strictEqual: (a: any, b: any) => boolean;
export declare const strictObjectIsEqual: (a: any, b: any) => boolean;
export declare const deepObjectStrictEqual: (object1: JSONSerializable, object2: JSONSerializable) => boolean;
export declare function reverseColor(oldColor: string): string;
export declare const isSameStructure: (objA: unknown, objB: unknown) => boolean;
export declare const isLeafParent: (obj: JSONObject) => boolean;
export declare const addDays: (date: Date, days: number) => Date;
export declare class WaitManager {
private _time30;
private readonly _nXSpeed;
constructor(nXSpeed?: number);
private _time1;
get time1(): number;
private _time2;
get time2(): number;
private _time3;
get time3(): number;
private _time4;
get time4(): number;
private _time10;
get time10(): number;
private _time20;
get time20(): number;
get time50(): number;
private _time60;
get time60(): number;
private _cusTime;
get cusTime(): number;
set cusTime(v: number);
}
export declare const wait: (ms: number, resolveValue?: any) => Promise<unknown>;
export declare function extractValue<Item>(data: {
key: string;
value: Item;
}[]): Item[];
export declare function keyValueToArray<Item>(data: {
[key: string]: Item;
}): Item[];
export declare function minuted(time: number): string;
export declare function randomDate(start?: Date, end?: Date, specificProbabilityStart?: Date, specificProbability?: number): Date;
export declare const capitalizeWords: (str: string) => string;
export declare const capitalizeFirstLetter: (str: string) => string;
export declare const comparerArray: <T>(otherArray: T[], limitKeys?: string[]) => (current: T) => boolean;
export declare const onlyInA: <T>(a: T[], b: T[]) => T[];
export declare const onlyInB: <T>(a: T[], b: T[]) => T[];
export declare const diffAB: <T>(a: T[], b: T[]) => T[];
export declare class StringUtil {
static toCamelCase(str: string): string;
static toSnakeCase(str: string): string;
static toPascalCase(str: string): string;
static toConstantCase(str: string): string;
static toKebabCase(str: string): string;
static toLowerCase(str: string): string;
static toTitleCase(str: string): string;
static toSentenceCase(str: string): string;
static toPathCase(str: string): string;
static toDotCase(str: string): string;
}
export type CaseType = 'camel' | 'snake' | 'pascal' | 'constant' | 'kebab' | 'lower' | 'title' | 'sentence' | 'path' | 'dot';
export declare const deepKeysConvert: (obj: any, toType?: CaseType) => any;
export declare const deepRemoveByKey: (obj: any, keysToBeRemoved: string[]) => any;
export declare const deepRenameKeys: (obj: JSONSerializable, keysMap: {
[x: string]: string;
}) => JSONSerializable;
export declare const deepReplaceValues: (obj: JSONSerializable, keyReducerMap: {
[x: string]: (item: JSONSerializable) => any;
}) => JSONSerializable;
export declare const deepAdd: (obj: JSONSerializable, keyReducerMap: {
[x: string]: (item: JSONSerializable) => any;
}, isItemRootParent?: boolean) => [] | JSONObject;
export declare const bunnyConsole: {
log: (headerLog?: string, ...args: any[]) => void;
warn: (headerLog?: string, ...args: any[]) => void;
error: (headerLog?: string, ...args: any[]) => void;
};
export declare const timeStart: () => number;
export declare const timeEnd: (startTime: number, headerLog?: string, consoleConditionFn?: ((timeSpent: number) => boolean) | undefined) => void;
export declare const arrayRemove: <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean) => T[];
export declare function memo(): (target: Object, propertyKey: string, descriptor: PropertyDescriptor) => void;
export declare function zip<T = number, T1 = number>(array1: T[], array2: T1[], options?: {
isToObj: boolean;
}): [T, T1][] | {
x: T;
y: T1;
}[];
/**

@@ -106,3 +10,3 @@ * data-structure-typed

*/
import { Thunk, ToThunkFn, TrlAsyncFn, TrlFn } from './types';
import type { Thunk, ToThunkFn, TrlAsyncFn, TrlFn } from './types';
export declare const THUNK_SYMBOL: unique symbol;

@@ -109,0 +13,0 @@ export declare const isThunk: (fnOrValue: any) => boolean;

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
// import _ from 'lodash';
// import type {AnyFunction, CaseType, JSONObject, JSONSerializable} from './types';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -49,13 +40,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {

@@ -86,18 +66,4 @@ var m = typeof Symbol === "function" && o[Symbol.iterator];

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.trampolineAsync = exports.trampoline = exports.toThunk = exports.isThunk = exports.THUNK_SYMBOL = exports.zip = exports.memo = exports.arrayRemove = exports.timeEnd = exports.timeStart = exports.bunnyConsole = exports.deepAdd = exports.deepReplaceValues = exports.deepRenameKeys = exports.deepRemoveByKey = exports.deepKeysConvert = exports.StringUtil = exports.diffAB = exports.onlyInB = exports.onlyInA = exports.comparerArray = exports.capitalizeFirstLetter = exports.capitalizeWords = exports.randomDate = exports.minuted = exports.keyValueToArray = exports.extractValue = exports.wait = exports.WaitManager = exports.addDays = exports.isLeafParent = exports.isSameStructure = exports.reverseColor = exports.deepObjectStrictEqual = exports.strictObjectIsEqual = exports.strictEqual = exports.looseEqual = exports.isObject = exports.getValue = exports.incrementId = exports.IncrementId = exports.uuidV4 = exports.randomText = void 0;
var lodash_1 = __importDefault(require("lodash"));
function randomText(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
exports.randomText = randomText;
exports.trampolineAsync = exports.trampoline = exports.toThunk = exports.isThunk = exports.THUNK_SYMBOL = exports.arrayRemove = exports.uuidV4 = void 0;
var uuidV4 = function () {

@@ -110,477 +76,197 @@ return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {

exports.uuidV4 = uuidV4;
var IncrementId = /** @class */ (function () {
function IncrementId(prefix) {
this._prefix = prefix ? prefix : '';
this._id = this._prefix + '0';
}
IncrementId.prototype.getId = function () {
var _a = this, _id = _a._id, _prefix = _a._prefix;
if (!_id) {
this._id = _prefix + '0';
}
else {
var idNumStr = _id.substr(_prefix.length, _id.length - _prefix.length);
var newIdNum = parseInt(idNumStr, 10) + 1;
this._id = _prefix + newIdNum.toString();
}
return this._id;
};
return IncrementId;
}());
exports.IncrementId = IncrementId;
function incrementId(prefix) {
var _prefix = prefix ? prefix : '';
var _id = _prefix + '0';
return function id() {
var idNumStr = _id.substr(_prefix.length, _id.length - _prefix.length);
var newIdNum = parseInt(idNumStr, 10) + 1;
_id = _prefix + newIdNum.toString();
return _id;
};
}
exports.incrementId = incrementId;
var getValue = function (obj, names) { return names.map(function (i) { return obj[i]; }); };
exports.getValue = getValue;
var isObject = function (object) { return object != null && typeof object === 'object'; };
exports.isObject = isObject;
var looseEqual = function (a, b) { return a == b; };
exports.looseEqual = looseEqual;
var strictEqual = function (a, b) { return a === b; };
exports.strictEqual = strictEqual;
var strictObjectIsEqual = function (a, b) { return Object.is(a, b); };
exports.strictObjectIsEqual = strictObjectIsEqual;
var deepObjectStrictEqual = function (object1, object2) {
var e_1, _a;
var keys1 = Object.keys(object1);
var keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
try {
for (var keys1_1 = __values(keys1), keys1_1_1 = keys1_1.next(); !keys1_1_1.done; keys1_1_1 = keys1_1.next()) {
var key = keys1_1_1.value;
var val1 = object1[key];
var val2 = object2[key];
var areObjects = (0, exports.isObject)(val1) && (0, exports.isObject)(val2);
if (areObjects && !(0, exports.deepObjectStrictEqual)(val1, val2) ||
!areObjects && val1 !== val2) {
return false;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (keys1_1_1 && !keys1_1_1.done && (_a = keys1_1.return)) _a.call(keys1_1);
}
finally { if (e_1) throw e_1.error; }
}
return true;
};
exports.deepObjectStrictEqual = deepObjectStrictEqual;
function reverseColor(oldColor) {
var oldColorTemp = '0x' + oldColor.replace(/#/g, '');
var str = '000000' + (0xFFFFFF - Number(oldColorTemp)).toString(16);
return '#' + str.substring(str.length - 6, str.length);
}
exports.reverseColor = reverseColor;
var isSameStructure = function (objA, objB) {
var objATraversable = objA;
var objBTraversable = objB;
var objAKeys = Object.keys(objATraversable);
var objBKeys = Object.keys(objBTraversable);
var isSame = true;
if (objAKeys.length !== objBKeys.length) {
return isSame = false;
}
else {
objAKeys.forEach(function (i) {
if (!objBKeys.includes(i)) {
return isSame = false;
}
});
return isSame;
}
};
exports.isSameStructure = isSameStructure;
var isLeafParent = function (obj) {
var isLeaf = true;
Object.values(obj).forEach(function (value) {
if (typeof value === 'object' && value instanceof Array) {
value.forEach(function (item) {
if (typeof item === 'object') {
return false;
}
});
return isLeaf = true;
}
if (!['string', 'boolean', 'number', 'undefined', 'function'].includes(typeof value) && (value !== null)) {
return isLeaf = false;
}
});
return isLeaf;
};
exports.isLeafParent = isLeafParent;
var addDays = function (date, days) {
date.setDate(date.getDate() + days);
return date;
};
exports.addDays = addDays;
var WaitManager = /** @class */ (function () {
function WaitManager(nXSpeed) {
this._time30 = 20000;
this._nXSpeed = 1;
this._time1 = 1000;
this._time2 = 2000;
this._time3 = 3000;
this._time4 = 4000;
this._time10 = 10000;
this._time20 = 20000;
this._time60 = 60000;
this._cusTime = 1000;
if (nXSpeed === undefined)
nXSpeed = 1;
this._nXSpeed = nXSpeed;
}
Object.defineProperty(WaitManager.prototype, "time1", {
get: function () {
return this._time1 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "time2", {
get: function () {
return this._time2 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "time3", {
get: function () {
return this._time3 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "time4", {
get: function () {
return this._time4 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "time10", {
get: function () {
return this._time10 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "time20", {
get: function () {
return this._time20 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "time50", {
get: function () {
return this._time30 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "time60", {
get: function () {
return this._time60 / this._nXSpeed;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaitManager.prototype, "cusTime", {
get: function () {
return this._cusTime / this._nXSpeed;
},
set: function (v) {
this._cusTime = v;
},
enumerable: false,
configurable: true
});
return WaitManager;
}());
exports.WaitManager = WaitManager;
var wait = function (ms, resolveValue) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
setTimeout(function () {
var finalResolveValue = resolveValue || true;
resolve(finalResolveValue);
}, ms);
})];
});
}); };
exports.wait = wait;
function extractValue(data) {
var result = [];
if (data && data.length > 0) {
result = data.map(function (item) { return item.value; });
}
return result;
}
exports.extractValue = extractValue;
function keyValueToArray(data) {
var e_2, _a;
var itemArray = [];
var keys = Object.keys(data);
try {
for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
var i = keys_1_1.value;
itemArray.push(__assign(__assign({}, data[i]), { _id: i }));
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
}
finally { if (e_2) throw e_2.error; }
}
return itemArray;
}
exports.keyValueToArray = keyValueToArray;
function minuted(time) {
var minutes = Math.floor(time / 60000).toString();
var seconds = Math.floor((time % 60000) / 1000).toString().padStart(2, '0');
return "".concat(minutes, ":").concat(seconds);
}
exports.minuted = minuted;
function randomDate(start, end, specificProbabilityStart, specificProbability) {
if (!start)
start = new Date('1970-1-1');
if (!end)
end = new Date();
if (specificProbabilityStart) {
if (!specificProbability)
specificProbability = 0.5;
if (Math.random() <= specificProbability) {
return new Date(specificProbabilityStart.getTime() + Math.random() * (end.getTime() - specificProbabilityStart.getTime()));
}
}
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
exports.randomDate = randomDate;
var capitalizeWords = function (str) { return str.replace(/(?:^|\s)\S/g, function (a) { return a.toUpperCase(); }); };
exports.capitalizeWords = capitalizeWords;
var capitalizeFirstLetter = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); };
exports.capitalizeFirstLetter = capitalizeFirstLetter;
var comparerArray = function (otherArray, limitKeys) {
return function (current) {
return otherArray.filter(function (other) {
if (!limitKeys) {
return lodash_1.default.isEqual(current, other);
}
else {
// TODO
}
}).length == 0;
};
};
exports.comparerArray = comparerArray;
var onlyInA = function (a, b) { return a.filter((0, exports.comparerArray)(b)); };
exports.onlyInA = onlyInA;
var onlyInB = function (a, b) { return b.filter((0, exports.comparerArray)(a)); };
exports.onlyInB = onlyInB;
var diffAB = function (a, b) { return (0, exports.onlyInA)(a, b).concat((0, exports.onlyInB)(a, b)); };
exports.diffAB = diffAB;
var StringUtil = /** @class */ (function () {
function StringUtil() {
}
// camelCase
StringUtil.toCamelCase = function (str) {
return lodash_1.default.camelCase(str);
};
// snake_case
StringUtil.toSnakeCase = function (str) {
return lodash_1.default.snakeCase(str);
};
// PascalCase
StringUtil.toPascalCase = function (str) {
return lodash_1.default.startCase(lodash_1.default.camelCase(str)).replace(/ /g, '');
};
// CONSTANT_CASE
StringUtil.toConstantCase = function (str) {
return lodash_1.default.upperCase(str).replace(/ /g, '_');
};
// kebab-case
StringUtil.toKebabCase = function (str) {
return lodash_1.default.kebabCase(str);
};
// lowercase
StringUtil.toLowerCase = function (str) {
return lodash_1.default.lowerCase(str).replace(/ /g, '');
};
// Title Case
StringUtil.toTitleCase = function (str) {
return lodash_1.default.startCase(lodash_1.default.camelCase(str));
};
// Sentence case
StringUtil.toSentenceCase = function (str) {
return lodash_1.default.upperFirst(lodash_1.default.lowerCase(str));
};
// path/case
StringUtil.toPathCase = function (str) {
return lodash_1.default.lowerCase(str).replace(/ /g, '/');
};
// dot.case
StringUtil.toDotCase = function (str) {
return lodash_1.default.lowerCase(str).replace(/ /g, '.');
};
return StringUtil;
}());
exports.StringUtil = StringUtil;
var deepKeysConvert = function (obj, toType) {
var _toType = toType || 'snake';
if (Array.isArray(obj)) {
return obj.map(function (v) { return (0, exports.deepKeysConvert)(v, _toType); });
}
else if (obj !== null && obj.constructor === Object) {
return Object.keys(obj).reduce(function (result, key) {
var _a;
var newKey = '';
switch (_toType) {
case 'camel':
newKey = StringUtil.toCamelCase(key);
break;
case 'snake':
newKey = StringUtil.toSnakeCase(key);
break;
case 'pascal':
newKey = StringUtil.toPascalCase(key);
break;
case 'constant':
newKey = StringUtil.toConstantCase(key);
break;
case 'kebab':
newKey = StringUtil.toKebabCase(key);
break;
case 'lower':
newKey = StringUtil.toLowerCase(key);
break;
case 'title':
newKey = StringUtil.toTitleCase(key);
break;
case 'sentence':
newKey = StringUtil.toSentenceCase(key);
break;
case 'path':
newKey = StringUtil.toPathCase(key);
break;
case 'dot':
newKey = StringUtil.toDotCase(key);
break;
default:
newKey = StringUtil.toDotCase(key);
break;
}
return __assign(__assign({}, result), (_a = {}, _a[newKey] = (0, exports.deepKeysConvert)(obj[key], _toType), _a));
}, {});
}
return obj;
};
exports.deepKeysConvert = deepKeysConvert;
var deepRemoveByKey = function (obj, keysToBeRemoved) {
var result = lodash_1.default.transform(obj, function (result, value, key) {
if (lodash_1.default.isObject(value)) {
value = (0, exports.deepRemoveByKey)(value, keysToBeRemoved);
}
if (!keysToBeRemoved.includes(key)) {
lodash_1.default.isArray(obj) ? result.push(value) : result[key] = value;
}
});
return result;
};
exports.deepRemoveByKey = deepRemoveByKey;
var deepRenameKeys = function (obj, keysMap) {
return lodash_1.default.transform(obj, function (result, value, key) {
var currentKey = keysMap[key] || key;
result[currentKey] = lodash_1.default.isObject(value) ? (0, exports.deepRenameKeys)(value, keysMap) : value;
});
};
exports.deepRenameKeys = deepRenameKeys;
var deepReplaceValues = function (obj, keyReducerMap) {
var newObject = lodash_1.default.clone(obj);
lodash_1.default.each(obj, function (val, key) {
for (var item in keyReducerMap) {
if (key === item) {
newObject[key] = keyReducerMap[item](newObject);
}
else if (typeof (val) === 'object' || val instanceof Array) {
newObject[key] = (0, exports.deepReplaceValues)(val, keyReducerMap);
}
}
});
return newObject;
};
exports.deepReplaceValues = deepReplaceValues;
// export const isObject = (object: string | JSONObject | boolean | AnyFunction | number) => object != null && typeof object === 'object';
// export const deepObjectStrictEqual = (object1: JSONSerializable, object2: JSONSerializable) => {
// const keys1 = Object.keys(object1);
// const keys2 = Object.keys(object2);
// if (keys1.length !== keys2.length) {
// return false;
// }
// for (const key of keys1) {
// const val1 = object1[key];
// const val2 = object2[key];
// const areObjects = isObject(val1) && isObject(val2);
// if (
// areObjects && !deepObjectStrictEqual(val1, val2) ||
// !areObjects && val1 !== val2
// ) {
// return false;
// }
// }
// return true;
// };
// export class StringUtil {
// // camelCase
// static toCamelCase(str: string) {
// return _.camelCase(str);
// }
//
// // snake_case
// static toSnakeCase(str: string) {
// return _.snakeCase(str);
// }
//
// // PascalCase
// static toPascalCase(str: string) {
// return _.startCase(_.camelCase(str)).replace(/ /g, '');
// }
//
// // CONSTANT_CASE
// static toConstantCase(str: string) {
// return _.upperCase(str).replace(/ /g, '_');
// }
//
// // kebab-case
// static toKebabCase(str: string) {
// return _.kebabCase(str);
// }
//
// // lowercase
// static toLowerCase(str: string) {
// return _.lowerCase(str).replace(/ /g, '');
// }
//
// // Title Case
// static toTitleCase(str: string) {
// return _.startCase(_.camelCase(str));
// }
//
// // Sentence case
// static toSentenceCase(str: string) {
// return _.upperFirst(_.lowerCase(str));
// }
//
// // path/case
// static toPathCase(str: string) {
// return _.lowerCase(str).replace(/ /g, '/');
// }
//
// // dot.case
// static toDotCase(str: string) {
// return _.lowerCase(str).replace(/ /g, '.');
// }
// }
// export const deepKeysConvert = (obj: any, toType?: CaseType): any => {
// const _toType = toType || 'snake';
// if (Array.isArray(obj)) {
// return obj.map(v => deepKeysConvert(v, _toType));
// } else if (obj !== null && obj.constructor === Object) {
// return Object.keys(obj).reduce(
// (result, key) => {
// let newKey = '';
// switch (_toType) {
// case 'camel':
// newKey = StringUtil.toCamelCase(key);
// break;
// case 'snake':
// newKey = StringUtil.toSnakeCase(key);
// break;
// case 'pascal':
// newKey = StringUtil.toPascalCase(key);
// break;
// case 'constant':
// newKey = StringUtil.toConstantCase(key);
// break;
// case 'kebab':
// newKey = StringUtil.toKebabCase(key);
// break;
// case 'lower':
// newKey = StringUtil.toLowerCase(key);
// break;
// case 'title':
// newKey = StringUtil.toTitleCase(key);
// break;
// case 'sentence':
// newKey = StringUtil.toSentenceCase(key);
// break;
// case 'path':
// newKey = StringUtil.toPathCase(key);
// break;
// case 'dot':
// newKey = StringUtil.toDotCase(key);
// break;
// default:
// newKey = StringUtil.toDotCase(key);
// break;
// }
// return {
// ...result,
// [newKey]: deepKeysConvert(obj[key], _toType),
// };
// },
// {},
// );
// }
// return obj;
// };
// export const deepRemoveByKey = (obj: any, keysToBeRemoved: string[]) => {
// const result = _.transform(obj, function (result: JSONSerializable, value: any, key: string) {
// if (_.isObject(value)) {
// value = deepRemoveByKey(value, keysToBeRemoved);
// }
// if (!keysToBeRemoved.includes(key)) {
// _.isArray(obj) ? result.push(value) : result[key] = value;
// }
// });
// return result as typeof obj;
// };
// export const deepRenameKeys = (obj: JSONSerializable, keysMap: { [key in string]: string }) => {
// return _.transform(obj, function (result: JSONSerializable, value: any, key: string | number) {
// const currentKey = keysMap[key] || key;
// result[currentKey] = _.isObject(value) ? deepRenameKeys(value, keysMap) : value;
// });
// };
// export const deepReplaceValues = (obj: JSONSerializable, keyReducerMap: { [key in string]: (item: JSONSerializable) => any }) => {
// const newObject = _.clone(obj) as JSONSerializable;
// _.each(obj, (val: any, key: string) => {
// for (const item in keyReducerMap) {
// if (key === item) {
// newObject[key] = keyReducerMap[item](newObject);
// } else if (typeof (val) === 'object' || val instanceof Array) {
// newObject[key] = deepReplaceValues(val, keyReducerMap);
// }
// }
// });
// return newObject;
// };
// TODO determine depth and pass root node as a param through callback
var deepAdd = function (obj, keyReducerMap, isItemRootParent) {
var newObject = lodash_1.default.clone(obj);
if (lodash_1.default.isObject(newObject) && !lodash_1.default.isArray(newObject)) {
for (var item in keyReducerMap) {
newObject[item] = keyReducerMap[item](newObject);
}
}
lodash_1.default.each(obj, function (val, key) {
if (lodash_1.default.isObject(val)) {
for (var item in keyReducerMap) {
// @ts-ignore
newObject[key] = (0, exports.deepAdd)(val, keyReducerMap, isItemRootParent);
}
}
});
return newObject;
};
exports.deepAdd = deepAdd;
var styleString = function (color) { return "color: ".concat(color, "; font-weight: bold"); };
var styleHeader = function (header) { return "%c[".concat(header, "]"); };
exports.bunnyConsole = {
log: function (headerLog) {
if (headerLog === void 0) { headerLog = 'bunny'; }
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return console.log.apply(console, __spreadArray([styleHeader(headerLog), styleString('black')], __read(args), false));
},
warn: function (headerLog) {
if (headerLog === void 0) { headerLog = 'bunny'; }
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return console.warn.apply(console, __spreadArray([styleHeader(headerLog), styleString('orange')], __read(args), false));
},
error: function (headerLog) {
if (headerLog === void 0) { headerLog = 'bunny'; }
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return console.error.apply(console, __spreadArray([styleHeader(headerLog), styleString('red')], __read(args), false));
}
};
var timeStart = function () {
return performance ? performance.now() : new Date().getTime();
};
exports.timeStart = timeStart;
var timeEnd = function (startTime, headerLog, consoleConditionFn) {
var timeSpent = (performance ? performance.now() : new Date().getTime()) - startTime;
var isPassCondition = consoleConditionFn ? consoleConditionFn(timeSpent) : true;
if (isPassCondition) {
exports.bunnyConsole.log(headerLog ? headerLog : 'time spent', timeSpent.toFixed(2));
}
};
exports.timeEnd = timeEnd;
// export const deepAdd = (obj: JSONSerializable, keyReducerMap: { [key in string]: (item: JSONSerializable) => any }, isItemRootParent?: boolean) => {
// const newObject = _.clone(obj) as JSONObject | [];
// if (_.isObject(newObject) && !_.isArray(newObject)) {
// for (const item in keyReducerMap) {
// newObject[item] = keyReducerMap[item](newObject);
// }
// }
// _.each(obj, (val: any, key: string | number) => {
// if (_.isObject(val)) {
// for (const item in keyReducerMap) {
// // @ts-ignore
// newObject[key] = deepAdd(val, keyReducerMap, isItemRootParent);
// }
// }
// });
// return newObject;
// };
// const styleString = (color: string) => `color: ${color}; font-weight: bold`;
// const styleHeader = (header: string) => `%c[${header}]`;
// export const bunnyConsole = {
// log: (headerLog = 'bunny', ...args: any[]) => {
// return console.log(styleHeader(headerLog), styleString('black'), ...args);
// },
// warn: (headerLog = 'bunny', ...args: any[]) => {
// return console.warn(styleHeader(headerLog), styleString('orange'), ...args);
// },
// error: (headerLog = 'bunny', ...args: any[]) => {
// return console.error(styleHeader(headerLog), styleString('red'), ...args);
// }
// };
// export const timeStart = () => {
// return performance ? performance.now() : new Date().getTime();
// };
// export const timeEnd = (startTime: number, headerLog?: string, consoleConditionFn?: (timeSpent: number) => boolean) => {
// const timeSpent = (performance ? performance.now() : new Date().getTime()) - startTime;
// const isPassCondition = consoleConditionFn ? consoleConditionFn(timeSpent) : true;
// if (isPassCondition) {
// bunnyConsole.log(headerLog ? headerLog : 'time spent', timeSpent.toFixed(2));
// }
// };
var arrayRemove = function (array, predicate) {

@@ -600,37 +286,2 @@ var i = -1, len = array ? array.length : 0;

exports.arrayRemove = arrayRemove;
function memo() {
var cache = {};
// eslint-disable-next-line @typescript-eslint/ban-types
return function (target, propertyKey, descriptor) {
var originalMethod = descriptor.value;
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var cacheKey = "__cacheKey__".concat(args.toString());
// eslint-disable-next-line no-prototype-builtins
if (!cache.hasOwnProperty(cacheKey)) {
cache[cacheKey] = originalMethod.apply(this, args);
}
return cache[cacheKey];
};
};
}
exports.memo = memo;
function zip(array1, array2, options) {
var zipped = [];
var zippedObjCoords = [];
var isToObj = (options ? options : { isToObj: false }).isToObj;
for (var i = 0; i < array1.length; i++) {
if (isToObj) {
zippedObjCoords.push({ x: array1[i], y: array2[i] });
}
else {
zipped.push([array1[i], array2[i]]);
}
}
return isToObj ? zippedObjCoords : zipped;
}
exports.zip = zip;
exports.THUNK_SYMBOL = Symbol('thunk');

@@ -637,0 +288,0 @@ var isThunk = function (fnOrValue) {

{
"name": "data-structure-typed",
"version": "1.15.0",
"version": "1.15.1",
"description": "Explore our comprehensive Javascript Data Structure / TypeScript Data Structure Library, meticulously crafted to empower developers with a versatile set of essential data structures. Our library includes a wide range of data structures, such as Binary Tree, AVL Tree, Binary Search Tree (BST), Tree Multiset, Segment Tree, Binary Indexed Tree, Graph, Directed Graph, Undirected Graph, Singly Linked List, Hash, CoordinateSet, CoordinateMap, Heap, Doubly Linked List, Priority Queue, Max Priority Queue, Min Priority Queue, Queue, ObjectDeque, ArrayDeque, Stack, and Trie. Each data structure is thoughtfully designed and implemented using TypeScript to provide efficient, reliable, and easy-to-use solutions for your programming needs. Whether you're optimizing algorithms, managing data, or enhancing performance, our TypeScript Data Structure Library is your go-to resource. Elevate your coding experience with these fundamental building blocks for software development.",

@@ -10,3 +10,4 @@ "main": "dist/index.js",

"build:docs": "typedoc --out docs ./src",
"deps:check": "dependency-cruiser src"
"deps:check": "dependency-cruiser src",
"build:publish": "npm run test && npm run build && npm run build:docs && npm run publish"
},

@@ -13,0 +14,0 @@ "repository": {

@@ -1,174 +0,161 @@

export type JSONSerializable = {
[key: string]: any
}
export type JSONValue = string | number | boolean | undefined | JSONObject;
// export type JSONSerializable = {
// [key: string]: any
// }
export interface JSONObject {
[key: string]: JSONValue;
}
// export type JSONValue = string | number | boolean | undefined | JSONObject;
//
// export interface JSONObject {
// [key: string]: JSONValue;
// }
//
// export type AnyFunction<A extends any[] = any[], R = any> = (...args: A) => R;
export type AnyFunction<A extends any[] = any[], R = any> = (...args: A) => R;
export type Primitive =
| number
| string
| boolean
| symbol
| undefined
| null
| void
| AnyFunction
| Date;
// export type Primitive =
// | number
// | string
// | boolean
// | symbol
// | undefined
// | null
// | void
// | AnyFunction
// | Date;
export type Cast<T, TComplex> = { [M in keyof TComplex]: T };
// export type Cast<T, TComplex> = { [M in keyof TComplex]: T };
// export type DeepLeavesWrap<T, TComplex> =
// T extends string ? Cast<string, TComplex>
// : T extends number ? Cast<number, TComplex>
// : T extends boolean ? Cast<boolean, TComplex>
// : T extends undefined ? Cast<undefined, TComplex>
// : T extends null ? Cast<null, TComplex>
// : T extends void ? Cast<void, TComplex>
// : T extends symbol ? Cast<symbol, TComplex>
// : T extends AnyFunction ? Cast<AnyFunction, TComplex>
// : T extends Date ? Cast<Date, TComplex>
// : {
// [K in keyof T]:
// T[K] extends (infer U)[] ? DeepLeavesWrap<U, TComplex>[]
// : DeepLeavesWrap<T[K], TComplex>;
// }
export type DeepLeavesWrap<T, TComplex> =
T extends string ? Cast<string, TComplex>
: T extends number ? Cast<number, TComplex>
: T extends boolean ? Cast<boolean, TComplex>
: T extends undefined ? Cast<undefined, TComplex>
: T extends null ? Cast<null, TComplex>
: T extends void ? Cast<void, TComplex>
: T extends symbol ? Cast<symbol, TComplex>
: T extends AnyFunction ? Cast<AnyFunction, TComplex>
: T extends Date ? Cast<Date, TComplex>
: {
[K in keyof T]:
T[K] extends (infer U)[] ? DeepLeavesWrap<U, TComplex>[]
: DeepLeavesWrap<T[K], TComplex>;
}
// type Json = null | string | number | boolean | Json [] | { [name: string]: Json }
type Json = null | string | number | boolean | Json [] | { [name: string]: Json }
// export type TypeName<T> = T extends string
// ? 'string'
// : T extends number
// ? 'number'
// : T extends boolean
// ? 'boolean'
// : T extends undefined
// ? 'undefined'
// : T extends AnyFunction
// ? 'function'
// : 'object';
export type TypeName<T> = T extends string
? 'string'
: T extends number
? 'number'
: T extends boolean
? 'boolean'
: T extends undefined
? 'undefined'
: T extends AnyFunction
? 'function'
: 'object';
// export type JsonKeys<T> = keyof {
// [P in keyof T]: number
// }
export type JsonKeys<T> = keyof {
[P in keyof T]: number
}
const arr = ['1', 2, 4, 5, 6] as const;
type Range = typeof arr[number];
const a: Range = 2;
/**
* A function that emits a side effect and does not return anything.
*/
export type Procedure = (...args: any[]) => void;
// export type Procedure = (...args: any[]) => void;
export type DebounceOptions = {
isImmediate?: boolean;
maxWait?: number;
};
// export type DebounceOptions = {
// isImmediate?: boolean;
// maxWait?: number;
// };
export interface DebouncedFunction<F extends Procedure> {
cancel: () => void;
// export interface DebouncedFunction<F extends Procedure> {
// cancel: () => void;
//
// (this: ThisParameterType<F>, ...args: [...Parameters<F>]): void;
// }
(this: ThisParameterType<F>, ...args: [...Parameters<F>]): void;
}
// export type MonthKey =
// 'January' |
// 'February' |
// 'March' |
// 'April' |
// 'May' |
// 'June' |
// 'July' |
// 'August' |
// 'September' |
// 'October' |
// 'November' |
// 'December';
export type MonthKey =
'January' |
'February' |
'March' |
'April' |
'May' |
'June' |
'July' |
'August' |
'September' |
'October' |
'November' |
'December';
// export type Month = { [key in MonthKey]: string }
export type Month = { [key in MonthKey]: string }
// export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
// export class TreeNode<T> {
// id: string;
// name?: string | undefined;
// value?: T | undefined;
// children?: TreeNode<T>[] | undefined;
//
// constructor(id: string, name?: string, value?: T, children?: TreeNode<T>[]) {
// this.id = id;
// this.name = name || '';
// this.value = value || undefined;
// this.children = children || [];
// }
//
// addChildren(children: TreeNode<T> | TreeNode<T> []) {
// if (!this.children) {
// this.children = [];
// }
// if (children instanceof TreeNode) {
// this.children.push(children);
// } else {
// this.children = this.children.concat(children);
// }
// }
//
// getHeight() {
// // eslint-disable-next-line @typescript-eslint/no-this-alias
// const beginRoot = this;
// let maxDepth = 1;
// if (beginRoot) {
// const bfs = (node: TreeNode<T>, level: number) => {
// if (level > maxDepth) {
// maxDepth = level;
// }
// const {children} = node;
// if (children) {
// for (let i = 0, len = children.length; i < len; i++) {
// bfs(children[i], level + 1);
// }
// }
// };
// bfs(beginRoot, 1);
// }
// return maxDepth;
// }
//
// }
export class TreeNode<T> {
id: string;
name?: string | undefined;
value?: T | undefined;
children?: TreeNode<T>[] | undefined;
// export type OrderType = 'InOrder' | 'PreOrder' | 'PostOrder'
constructor(id: string, name?: string, value?: T, children?: TreeNode<T>[]) {
this.id = id;
this.name = name || '';
this.value = value || undefined;
this.children = children || [];
}
// export type DeepProxy<T> = T extends (...args: any[]) => infer R
// ? (...args: [...Parameters<T>]) => DeepProxy<R>
// : T extends object
// ? { [K in keyof T]: DeepProxy<T[K]> }
// : T;
// TODO get set
// get name (): string | undefined {
// return this.name;
// }
//
// set name (name: string | undefined) {
// this.name = name;
// }
// export type DeepProxyOnChange = (target: any, property: string | symbol, value: any, receiver: any, descriptor: any, result: any) => void;
addChildren(children: TreeNode<T> | TreeNode<T> []) {
if (!this.children) {
this.children = [];
}
if (children instanceof TreeNode) {
this.children.push(children);
} else {
this.children = this.children.concat(children);
}
}
// export type DeepProxyOnGet = (target: any, property: string | symbol, value: any, receiver: any, descriptor: any, result: any) => void;
getHeight() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const beginRoot = this;
let maxDepth = 1;
if (beginRoot) {
const bfs = (node: TreeNode<T>, level: number) => {
if (level > maxDepth) {
maxDepth = level;
}
const {children} = node;
if (children) {
for (let i = 0, len = children.length; i < len; i++) {
bfs(children[i], level + 1);
}
}
};
bfs(beginRoot, 1);
}
return maxDepth;
}
// export type CurryFunc<T> = T extends (...args: infer Args) => infer R
// ? Args extends [infer Arg, ...infer RestArgs]
// ? (arg: Arg) => CurryFunc<(...args: RestArgs) => R>
// : R
// : T;
}
export type OrderType = 'InOrder' | 'PreOrder' | 'PostOrder'
export type DeepProxy<T> = T extends (...args: any[]) => infer R
? (...args: [...Parameters<T>]) => DeepProxy<R>
: T extends object
? { [K in keyof T]: DeepProxy<T[K]> }
: T;
export type DeepProxyOnChange = (target: any, property: string | symbol, value: any, receiver: any, descriptor: any, result: any) => void;
export type DeepProxyOnGet = (target: any, property: string | symbol, value: any, receiver: any, descriptor: any, result: any) => void;
export type CurryFunc<T> = T extends (...args: infer Args) => infer R
? Args extends [infer Arg, ...infer RestArgs]
? (arg: Arg) => CurryFunc<(...args: RestArgs) => R>
: R
: T;
export type ToThunkFn = () => ReturnType<TrlFn>;

@@ -179,1 +166,12 @@ export type Thunk = () => ReturnType<ToThunkFn> & { __THUNK__: Symbol };

// export type CaseType =
// 'camel'
// | 'snake'
// | 'pascal'
// | 'constant'
// | 'kebab'
// | 'lower'
// | 'title'
// | 'sentence'
// | 'path'
// | 'dot';

@@ -1,14 +0,4 @@

import _ from 'lodash';
import type {AnyFunction, JSONObject, JSONSerializable} from './types';
// import _ from 'lodash';
// import type {AnyFunction, CaseType, JSONObject, JSONSerializable} from './types';
export function randomText(length: number) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export const uuidV4 = function () {

@@ -21,442 +11,210 @@ return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {

export class IncrementId {
private _id: string;
private readonly _prefix: string;
// export const isObject = (object: string | JSONObject | boolean | AnyFunction | number) => object != null && typeof object === 'object';
constructor(prefix?: string) {
this._prefix = prefix ? prefix : '';
this._id = this._prefix + '0';
}
// export const deepObjectStrictEqual = (object1: JSONSerializable, object2: JSONSerializable) => {
// const keys1 = Object.keys(object1);
// const keys2 = Object.keys(object2);
// if (keys1.length !== keys2.length) {
// return false;
// }
// for (const key of keys1) {
// const val1 = object1[key];
// const val2 = object2[key];
// const areObjects = isObject(val1) && isObject(val2);
// if (
// areObjects && !deepObjectStrictEqual(val1, val2) ||
// !areObjects && val1 !== val2
// ) {
// return false;
// }
// }
// return true;
// };
getId() {
const {_id, _prefix} = this;
if (!_id) {
this._id = _prefix + '0';
} else {
const idNumStr = _id.substr(_prefix.length, _id.length - _prefix.length);
const newIdNum = parseInt(idNumStr, 10) + 1;
this._id = _prefix + newIdNum.toString();
}
return this._id;
}
}
// export class StringUtil {
// // camelCase
// static toCamelCase(str: string) {
// return _.camelCase(str);
// }
//
// // snake_case
// static toSnakeCase(str: string) {
// return _.snakeCase(str);
// }
//
// // PascalCase
// static toPascalCase(str: string) {
// return _.startCase(_.camelCase(str)).replace(/ /g, '');
// }
//
// // CONSTANT_CASE
// static toConstantCase(str: string) {
// return _.upperCase(str).replace(/ /g, '_');
// }
//
// // kebab-case
// static toKebabCase(str: string) {
// return _.kebabCase(str);
// }
//
// // lowercase
// static toLowerCase(str: string) {
// return _.lowerCase(str).replace(/ /g, '');
// }
//
// // Title Case
// static toTitleCase(str: string) {
// return _.startCase(_.camelCase(str));
// }
//
// // Sentence case
// static toSentenceCase(str: string) {
// return _.upperFirst(_.lowerCase(str));
// }
//
// // path/case
// static toPathCase(str: string) {
// return _.lowerCase(str).replace(/ /g, '/');
// }
//
// // dot.case
// static toDotCase(str: string) {
// return _.lowerCase(str).replace(/ /g, '.');
// }
// }
export function incrementId(prefix?: string) {
const _prefix = prefix ? prefix : '';
let _id = _prefix + '0';
return function id() {
const idNumStr = _id.substr(_prefix.length, _id.length - _prefix.length);
const newIdNum = parseInt(idNumStr, 10) + 1;
_id = _prefix + newIdNum.toString();
return _id;
};
}
export const getValue = <T, K extends keyof T>(obj: T, names: K[]): Array<T[K]> => names.map(i => obj[i]);
// export const deepKeysConvert = (obj: any, toType?: CaseType): any => {
// const _toType = toType || 'snake';
// if (Array.isArray(obj)) {
// return obj.map(v => deepKeysConvert(v, _toType));
// } else if (obj !== null && obj.constructor === Object) {
// return Object.keys(obj).reduce(
// (result, key) => {
// let newKey = '';
// switch (_toType) {
// case 'camel':
// newKey = StringUtil.toCamelCase(key);
// break;
// case 'snake':
// newKey = StringUtil.toSnakeCase(key);
// break;
// case 'pascal':
// newKey = StringUtil.toPascalCase(key);
// break;
// case 'constant':
// newKey = StringUtil.toConstantCase(key);
// break;
// case 'kebab':
// newKey = StringUtil.toKebabCase(key);
// break;
// case 'lower':
// newKey = StringUtil.toLowerCase(key);
// break;
// case 'title':
// newKey = StringUtil.toTitleCase(key);
// break;
// case 'sentence':
// newKey = StringUtil.toSentenceCase(key);
// break;
// case 'path':
// newKey = StringUtil.toPathCase(key);
// break;
// case 'dot':
// newKey = StringUtil.toDotCase(key);
// break;
// default:
// newKey = StringUtil.toDotCase(key);
// break;
// }
// return {
// ...result,
// [newKey]: deepKeysConvert(obj[key], _toType),
// };
// },
// {},
// );
// }
// return obj;
// };
export const isObject = (object: string | JSONObject | boolean | AnyFunction | number) => object != null && typeof object === 'object';
// export const deepRemoveByKey = (obj: any, keysToBeRemoved: string[]) => {
// const result = _.transform(obj, function (result: JSONSerializable, value: any, key: string) {
// if (_.isObject(value)) {
// value = deepRemoveByKey(value, keysToBeRemoved);
// }
// if (!keysToBeRemoved.includes(key)) {
// _.isArray(obj) ? result.push(value) : result[key] = value;
// }
// });
// return result as typeof obj;
// };
export const looseEqual = (a: any, b: any): boolean => a == b;
// export const deepRenameKeys = (obj: JSONSerializable, keysMap: { [key in string]: string }) => {
// return _.transform(obj, function (result: JSONSerializable, value: any, key: string | number) {
// const currentKey = keysMap[key] || key;
// result[currentKey] = _.isObject(value) ? deepRenameKeys(value, keysMap) : value;
// });
// };
export const strictEqual = (a: any, b: any): boolean => a === b;
// export const deepReplaceValues = (obj: JSONSerializable, keyReducerMap: { [key in string]: (item: JSONSerializable) => any }) => {
// const newObject = _.clone(obj) as JSONSerializable;
// _.each(obj, (val: any, key: string) => {
// for (const item in keyReducerMap) {
// if (key === item) {
// newObject[key] = keyReducerMap[item](newObject);
// } else if (typeof (val) === 'object' || val instanceof Array) {
// newObject[key] = deepReplaceValues(val, keyReducerMap);
// }
// }
// });
// return newObject;
// };
export const strictObjectIsEqual = (a: any, b: any): boolean => Object.is(a, b);
export const deepObjectStrictEqual = (object1: JSONSerializable, object2: JSONSerializable) => {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
const val1 = object1[key];
const val2 = object2[key];
const areObjects = isObject(val1) && isObject(val2);
if (
areObjects && !deepObjectStrictEqual(val1, val2) ||
!areObjects && val1 !== val2
) {
return false;
}
}
return true;
};
export function reverseColor(oldColor: string) {
const oldColorTemp = '0x' + oldColor.replace(/#/g, '');
const str = '000000' + (0xFFFFFF - Number(oldColorTemp)).toString(16);
return '#' + str.substring(str.length - 6, str.length);
}
export const isSameStructure = (objA: unknown, objB: unknown) => {
const objATraversable = objA as JSONSerializable;
const objBTraversable = objB as JSONSerializable;
const objAKeys = Object.keys(objATraversable);
const objBKeys = Object.keys(objBTraversable);
let isSame = true;
if (objAKeys.length !== objBKeys.length) {
return isSame = false;
} else {
objAKeys.forEach((i) => {
if (!objBKeys.includes(i)) {
return isSame = false;
}
});
return isSame;
}
};
export const isLeafParent = (obj: JSONObject) => {
let isLeaf = true;
Object.values(obj).forEach(value => {
if (typeof value === 'object' && value instanceof Array) {
value.forEach(item => {
if (typeof item === 'object') {
return false;
}
});
return isLeaf = true;
}
if (!['string', 'boolean', 'number', 'undefined', 'function'].includes(typeof value) && (value !== null)) {
return isLeaf = false;
}
});
return isLeaf;
};
export const addDays = (date: Date, days: number): Date => {
date.setDate(date.getDate() + days);
return date;
};
export class WaitManager {
private _time30 = 20000;
private readonly _nXSpeed: number = 1;
constructor(nXSpeed?: number) {
if (nXSpeed === undefined) nXSpeed = 1;
this._nXSpeed = nXSpeed;
}
private _time1 = 1000;
get time1(): number {
return this._time1 / this._nXSpeed;
}
private _time2 = 2000;
get time2(): number {
return this._time2 / this._nXSpeed;
}
private _time3 = 3000;
get time3(): number {
return this._time3 / this._nXSpeed;
}
private _time4 = 4000;
get time4(): number {
return this._time4 / this._nXSpeed;
}
private _time10 = 10000;
get time10(): number {
return this._time10 / this._nXSpeed;
}
private _time20 = 20000;
get time20(): number {
return this._time20 / this._nXSpeed;
}
get time50(): number {
return this._time30 / this._nXSpeed;
}
private _time60 = 60000;
get time60(): number {
return this._time60 / this._nXSpeed;
}
private _cusTime = 1000;
get cusTime(): number {
return this._cusTime / this._nXSpeed;
}
set cusTime(v: number) {
this._cusTime = v;
}
}
export const wait = async (ms: number, resolveValue?: any) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const finalResolveValue = resolveValue || true;
resolve(finalResolveValue);
}, ms);
});
};
export function extractValue<Item>(data: { key: string, value: Item }[]) {
let result: Item[] = [];
if (data && data.length > 0) {
result = data.map(item => item.value);
}
return result;
}
export function keyValueToArray<Item>(data: { [key: string]: Item }) {
const itemArray: Array<Item> = [];
const keys = Object.keys(data);
for (const i of keys) {
itemArray.push({...data[i], _id: i});
}
return itemArray;
}
export function minuted(time: number) {
const minutes = Math.floor(time / 60000).toString();
const seconds = Math.floor((time % 60000) / 1000).toString().padStart(2, '0');
return `${minutes}:${seconds}`;
}
export function randomDate(start?: Date, end?: Date, specificProbabilityStart?: Date, specificProbability?: number) {
if (!start) start = new Date('1970-1-1');
if (!end) end = new Date();
if (specificProbabilityStart) {
if (!specificProbability) specificProbability = 0.5;
if (Math.random() <= specificProbability) {
return new Date(specificProbabilityStart.getTime() + Math.random() * (end.getTime() - specificProbabilityStart.getTime()));
}
}
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
export const capitalizeWords = (str: string) => str.replace(/(?:^|\s)\S/g, (a: string) => a.toUpperCase());
export const capitalizeFirstLetter = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
export const comparerArray = <T>(otherArray: T[], limitKeys?: string[]) => {
return function (current: T) {
return otherArray.filter(function (other: T) {
if (!limitKeys) {
return _.isEqual(current, other);
} else {
// TODO
}
}).length == 0;
};
};
export const onlyInA = <T>(a: T[], b: T[]) => a.filter(comparerArray(b));
export const onlyInB = <T>(a: T[], b: T[]) => b.filter(comparerArray(a));
export const diffAB = <T>(a: T[], b: T[]) => onlyInA(a, b).concat(onlyInB(a, b));
export class StringUtil {
// camelCase
static toCamelCase(str: string) {
return _.camelCase(str);
}
// snake_case
static toSnakeCase(str: string) {
return _.snakeCase(str);
}
// PascalCase
static toPascalCase(str: string) {
return _.startCase(_.camelCase(str)).replace(/ /g, '');
}
// CONSTANT_CASE
static toConstantCase(str: string) {
return _.upperCase(str).replace(/ /g, '_');
}
// kebab-case
static toKebabCase(str: string) {
return _.kebabCase(str);
}
// lowercase
static toLowerCase(str: string) {
return _.lowerCase(str).replace(/ /g, '');
}
// Title Case
static toTitleCase(str: string) {
return _.startCase(_.camelCase(str));
}
// Sentence case
static toSentenceCase(str: string) {
return _.upperFirst(_.lowerCase(str));
}
// path/case
static toPathCase(str: string) {
return _.lowerCase(str).replace(/ /g, '/');
}
// dot.case
static toDotCase(str: string) {
return _.lowerCase(str).replace(/ /g, '.');
}
}
export type CaseType =
'camel'
| 'snake'
| 'pascal'
| 'constant'
| 'kebab'
| 'lower'
| 'title'
| 'sentence'
| 'path'
| 'dot';
export const deepKeysConvert = (obj: any, toType?: CaseType): any => {
const _toType = toType || 'snake';
if (Array.isArray(obj)) {
return obj.map(v => deepKeysConvert(v, _toType));
} else if (obj !== null && obj.constructor === Object) {
return Object.keys(obj).reduce(
(result, key) => {
let newKey = '';
switch (_toType) {
case 'camel':
newKey = StringUtil.toCamelCase(key);
break;
case 'snake':
newKey = StringUtil.toSnakeCase(key);
break;
case 'pascal':
newKey = StringUtil.toPascalCase(key);
break;
case 'constant':
newKey = StringUtil.toConstantCase(key);
break;
case 'kebab':
newKey = StringUtil.toKebabCase(key);
break;
case 'lower':
newKey = StringUtil.toLowerCase(key);
break;
case 'title':
newKey = StringUtil.toTitleCase(key);
break;
case 'sentence':
newKey = StringUtil.toSentenceCase(key);
break;
case 'path':
newKey = StringUtil.toPathCase(key);
break;
case 'dot':
newKey = StringUtil.toDotCase(key);
break;
default:
newKey = StringUtil.toDotCase(key);
break;
}
return {
...result,
[newKey]: deepKeysConvert(obj[key], _toType),
};
},
{},
);
}
return obj;
};
export const deepRemoveByKey = (obj: any, keysToBeRemoved: string[]) => {
const result = _.transform(obj, function (result: JSONSerializable, value: any, key: string) {
if (_.isObject(value)) {
value = deepRemoveByKey(value, keysToBeRemoved);
}
if (!keysToBeRemoved.includes(key)) {
_.isArray(obj) ? result.push(value) : result[key] = value;
}
});
return result as typeof obj;
};
export const deepRenameKeys = (obj: JSONSerializable, keysMap: { [key in string]: string }) => {
return _.transform(obj, function (result: JSONSerializable, value: any, key: string | number) {
const currentKey = keysMap[key] || key;
result[currentKey] = _.isObject(value) ? deepRenameKeys(value, keysMap) : value;
});
};
export const deepReplaceValues = (obj: JSONSerializable, keyReducerMap: { [key in string]: (item: JSONSerializable) => any }) => {
const newObject = _.clone(obj) as JSONSerializable;
_.each(obj, (val: any, key: string) => {
for (const item in keyReducerMap) {
if (key === item) {
newObject[key] = keyReducerMap[item](newObject);
} else if (typeof (val) === 'object' || val instanceof Array) {
newObject[key] = deepReplaceValues(val, keyReducerMap);
}
}
});
return newObject;
};
// TODO determine depth and pass root node as a param through callback
export const deepAdd = (obj: JSONSerializable, keyReducerMap: { [key in string]: (item: JSONSerializable) => any }, isItemRootParent?: boolean) => {
const newObject = _.clone(obj) as JSONObject | [];
if (_.isObject(newObject) && !_.isArray(newObject)) {
for (const item in keyReducerMap) {
newObject[item] = keyReducerMap[item](newObject);
}
}
_.each(obj, (val: any, key: string | number) => {
if (_.isObject(val)) {
for (const item in keyReducerMap) {
// @ts-ignore
newObject[key] = deepAdd(val, keyReducerMap, isItemRootParent);
}
}
});
return newObject;
};
// export const deepAdd = (obj: JSONSerializable, keyReducerMap: { [key in string]: (item: JSONSerializable) => any }, isItemRootParent?: boolean) => {
// const newObject = _.clone(obj) as JSONObject | [];
// if (_.isObject(newObject) && !_.isArray(newObject)) {
// for (const item in keyReducerMap) {
// newObject[item] = keyReducerMap[item](newObject);
// }
// }
// _.each(obj, (val: any, key: string | number) => {
// if (_.isObject(val)) {
// for (const item in keyReducerMap) {
// // @ts-ignore
// newObject[key] = deepAdd(val, keyReducerMap, isItemRootParent);
// }
// }
// });
// return newObject;
// };
const styleString = (color: string) => `color: ${color}; font-weight: bold`;
// const styleString = (color: string) => `color: ${color}; font-weight: bold`;
const styleHeader = (header: string) => `%c[${header}]`;
// const styleHeader = (header: string) => `%c[${header}]`;
export const bunnyConsole = {
log: (headerLog = 'bunny', ...args: any[]) => {
return console.log(styleHeader(headerLog), styleString('black'), ...args);
},
warn: (headerLog = 'bunny', ...args: any[]) => {
return console.warn(styleHeader(headerLog), styleString('orange'), ...args);
},
error: (headerLog = 'bunny', ...args: any[]) => {
return console.error(styleHeader(headerLog), styleString('red'), ...args);
}
};
// export const bunnyConsole = {
// log: (headerLog = 'bunny', ...args: any[]) => {
// return console.log(styleHeader(headerLog), styleString('black'), ...args);
// },
// warn: (headerLog = 'bunny', ...args: any[]) => {
// return console.warn(styleHeader(headerLog), styleString('orange'), ...args);
// },
// error: (headerLog = 'bunny', ...args: any[]) => {
// return console.error(styleHeader(headerLog), styleString('red'), ...args);
// }
// };
export const timeStart = () => {
return performance ? performance.now() : new Date().getTime();
};
// export const timeStart = () => {
// return performance ? performance.now() : new Date().getTime();
// };
export const timeEnd = (startTime: number, headerLog?: string, consoleConditionFn?: (timeSpent: number) => boolean) => {
const timeSpent = (performance ? performance.now() : new Date().getTime()) - startTime;
const isPassCondition = consoleConditionFn ? consoleConditionFn(timeSpent) : true;
if (isPassCondition) {
bunnyConsole.log(headerLog ? headerLog : 'time spent', timeSpent.toFixed(2));
}
};
// export const timeEnd = (startTime: number, headerLog?: string, consoleConditionFn?: (timeSpent: number) => boolean) => {
// const timeSpent = (performance ? performance.now() : new Date().getTime()) - startTime;
// const isPassCondition = consoleConditionFn ? consoleConditionFn(timeSpent) : true;
// if (isPassCondition) {
// bunnyConsole.log(headerLog ? headerLog : 'time spent', timeSpent.toFixed(2));
// }
// };

@@ -479,32 +237,3 @@ export const arrayRemove = function <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): T[] {

export function memo() {
const cache: { [k: string]: any } = {};
// eslint-disable-next-line @typescript-eslint/ban-types
return function (target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const cacheKey = `__cacheKey__${args.toString()}`;
// eslint-disable-next-line no-prototype-builtins
if (!cache.hasOwnProperty(cacheKey)) {
cache[cacheKey] = originalMethod.apply(this, args);
}
return cache[cacheKey];
}
}
}
export function zip<T = number, T1 = number>(array1: T[], array2: T1[], options?: { isToObj: boolean }) {
const zipped: [T, T1][] = [];
const zippedObjCoords: { x: T, y: T1 }[] = [];
const {isToObj} = options ? options : {isToObj: false};
for (let i = 0; i < array1.length; i++) {
if (isToObj) {
zippedObjCoords.push({x: array1[i], y: array2[i]})
} else {
zipped.push([array1[i], array2[i]]);
}
}
return isToObj ? zippedObjCoords : zipped;
}
/**

@@ -517,3 +246,3 @@ * data-structure-typed

*/
import {Thunk, ToThunkFn, TrlAsyncFn, TrlFn} from './types';
import type {Thunk, ToThunkFn, TrlAsyncFn, TrlFn} from './types';

@@ -520,0 +249,0 @@ export const THUNK_SYMBOL = Symbol('thunk')

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