Added timeToMilliseconds, eslint and tidied up some old bits of code

This commit is contained in:
Martin Donnelly 2023-04-30 17:32:28 +01:00
parent 302c0a897b
commit d325808101
18 changed files with 4020 additions and 30 deletions

60
.eslintrc.cjs Normal file
View File

@ -0,0 +1,60 @@
module.exports = {
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
root: true,
env: {
'node': true,
'es2018': true,
},
rules: {
'no-shadow': ['error', { 'hoist': 'all' }],
'@typescript-eslint/no-shadow': ['error'],
'no-multi-spaces': 'error',
'no-multiple-empty-lines': ['error', { 'max': 1, 'maxEOF': 1 }],
'spaced-comment': ['error', 'always', { 'markers': ['/'] }],
'semi': 'error',
'arrow-spacing': 'error',
'block-scoped-var': 'error',
'block-spacing': 'error',
'brace-style': ['error', '1tbs', {}],
'camelcase': 'error',
'comma-spacing': ['error', { 'before': false, 'after': true }],
'comma-style': ['error', 'last'],
'consistent-this': ['error', '_this'],
'curly': ['error', 'multi'],
'eol-last': ['error', 'always'],
'eqeqeq': ['error', 'always'],
'func-names': ['error', 'as-needed'],
'indent': ['error', 2, { 'SwitchCase': 1 }],
'max-len': [
'error',
{
'code': 160,
'tabWidth': 2,
'ignoreComments': true,
'ignoreTrailingComments': true,
'ignoreUrls': true,
'ignoreStrings': true,
'ignoreTemplateLiterals': true,
'ignoreRegExpLiterals': true,
},
],
'new-cap': 'error',
'newline-before-return': 'error',
'no-array-constructor': 'error',
'no-inner-declarations': ['error', 'both'],
'no-new-object': 'error',
'no-shadow-restricted-names': 'error',
'object-curly-spacing': ['error', 'always'],
'prefer-const': 'error',
'prefer-template': 'error',
'one-var': ['error', { 'initialized': 'never' }],
'quote-props': ['error', 'always'],
'quotes': ['error', 'single'],
'radix': 'error',
'space-before-blocks': ['error', 'always'],
'space-infix-ops': 'error',
'vars-on-top': 'error',
},
};

View File

@ -1,6 +1,6 @@
{ {
"name": "@rakh/utils", "name": "@rakh/utils",
"version": "2.0.14", "version": "2.0.16",
"main": "dist/commonjs/index.js", "main": "dist/commonjs/index.js",
"types": "dist/commonjs/index.d.ts", "types": "dist/commonjs/index.d.ts",
"module": "dist/es/index.js", "module": "dist/es/index.js",
@ -37,6 +37,9 @@
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.0", "@types/jest": "^29.5.0",
"@types/sinon": "^10.0.13", "@types/sinon": "^10.0.13",
"@typescript-eslint/eslint-plugin": "^5.59.1",
"@typescript-eslint/parser": "^5.59.1",
"eslint": "^8.39.0",
"grunt": "^1.6.1", "grunt": "^1.6.1",
"jest": "^29.5.0", "jest": "^29.5.0",
"marked": "^4.3.0", "marked": "^4.3.0",

3817
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -6,10 +6,11 @@
* @example * @example
* U.arrayFromObj({ a: 1, b: 2 }, ['a', 'b']) // => [1, 2] * U.arrayFromObj({ a: 1, b: 2 }, ['a', 'b']) // => [1, 2]
*/ */
export function arrayFromObj(jsonObj: Object, wantedFields: string[]): any[] { export function arrayFromObj(jsonObj: object, wantedFields: string[]): any[] {
return wantedFields.map((key) => { return wantedFields.map((key) => {
if (jsonObj.hasOwnProperty(key)) { if (jsonObj.hasOwnProperty(key)) {
const { value }: any = Object.getOwnPropertyDescriptor(jsonObj, key); const { value }: any = Object.getOwnPropertyDescriptor(jsonObj, key);
return value; return value;
} }
}); });

View File

@ -36,16 +36,16 @@ export function distance(latLong1: LatLong, latLong2: LatLong): number;
* Calculate the Distance between two lat long points * Calculate the Distance between two lat long points
*/ */
export function distance(): number { export function distance(): number {
if (arguments.length === 4) { if (arguments.length === 4)
return _distance(arguments[0], arguments[1], arguments[2], arguments[3]); return _distance(arguments[0], arguments[1], arguments[2], arguments[3]);
} else if (arguments.length === 2) { else if (arguments.length === 2)
return _distance( return _distance(
<number>arguments[0].lat, <number>arguments[0].lat,
<number>arguments[0].long, <number>arguments[0].long,
<number>arguments[1].lat, <number>arguments[1].lat,
<number>arguments[1].long <number>arguments[1].long
); );
} else return 0; else return 0;
} }
function _distance(lat1: number, lon1: number, lat2: number, lon2: number): number { function _distance(lat1: number, lon1: number, lat2: number, lon2: number): number {

View File

@ -9,16 +9,16 @@
* U.extractFromObj({ a: 1, b: 2 }, ['a']) // => { a: 1 } * U.extractFromObj({ a: 1, b: 2 }, ['a']) // => { a: 1 }
* *
*/ */
export function extractFromObj(jsonObj: Object, wantedFields: string[]): {} { export function extractFromObj(jsonObj: object, wantedFields: string[]): object {
return Object.keys(jsonObj).reduce((obj, key) => { return Object.keys(jsonObj).reduce((obj, key) => {
if (wantedFields.includes(key)) { if (wantedFields.includes(key)) {
const { value }: any = Object.getOwnPropertyDescriptor(jsonObj, key); const { value }: any = Object.getOwnPropertyDescriptor(jsonObj, key);
Object.defineProperty(obj, key, { Object.defineProperty(obj, key, {
value: value, 'value': value,
writable: true, 'writable': true,
enumerable: true, 'enumerable': true,
configurable: true 'configurable': true
}); });
} }

View File

@ -7,18 +7,19 @@
* @example * @example
* U.get({ a: 1, b: 2 }, 'b') // => 2 * U.get({ a: 1, b: 2 }, 'b') // => 2
*/ */
export function get(obj: Object, path: string, defaultValue: any = undefined): any { export function get(obj: object, path: string, defaultValue: unknown = undefined): unknown {
const travel = (regexp: any) => { const travel = (regexp: RegExp) => {
return String.prototype.split return String.prototype.split
.call(path, regexp) .call(path, regexp)
.filter(Boolean) .filter(Boolean)
.reduce((res, key) => { .reduce((res, key) => {
if (res !== null && res !== undefined && res.hasOwnProperty(key)) { if (res !== null && res !== undefined && res.hasOwnProperty(key)) {
const { value }: any = Object.getOwnPropertyDescriptor(res, key); const { value }: any = Object.getOwnPropertyDescriptor(res, key);
return value; return value;
} else { } else
return res; return res;
}
}, obj); }, obj);
}; };
const result = travel(/[,[\].]+?/); const result = travel(/[,[\].]+?/);

View File

@ -5,10 +5,8 @@
*/ */
export function getDays(startdate: Date, enddate: Date): number { export function getDays(startdate: Date, enddate: Date): number {
let result, startMS, endMS; const startMS = startdate.getTime();
startMS = startdate.getTime(); const endMS = enddate.getTime();
endMS = enddate.getTime();
result = Math.ceil((endMS - startMS) / (24 * 60 * 60 * 1000));
return result; return Math.ceil((endMS - startMS) / (24 * 60 * 60 * 1000));
} }

View File

@ -9,6 +9,6 @@ const hasOwnProperty = Object.prototype.hasOwnProperty;
* @example * @example
* U.hasOwn({bob:'1'}, 'bob') // => true * U.hasOwn({bob:'1'}, 'bob') // => true
*/ */
export function hasOwn(obj: Object, prop: string): boolean { export function hasOwn(obj: object, prop: string): boolean {
return hasOwnProperty.call(obj, prop); return hasOwnProperty.call(obj, prop);
} }

View File

@ -14,4 +14,5 @@ export * from './maybePluralize';
export * from './once'; export * from './once';
export * from './partOfDay'; export * from './partOfDay';
export * from './throttle'; export * from './throttle';
export * from './timeToMilliseconds';
export * from './toHour'; export * from './toHour';

View File

@ -6,7 +6,7 @@
* U.isEmpty({}) // => true * U.isEmpty({}) // => true
* U.isEmpty({ bob: true }) // => false * U.isEmpty({ bob: true }) // => false
*/ */
export function isEmpty(obj: Object): boolean { export function isEmpty(obj: object): boolean {
// @ts-ignore // @ts-ignore
return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length; return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
} }

View File

@ -1,5 +1,5 @@
export class limitedArray { export class limitedArray {
_array: any[]; _array: unknown[];
_limit: number; _limit: number;
/** /**
@ -17,7 +17,7 @@ export class limitedArray {
* @param item * @param item
*/ */
push(item: any): void { push(item: unknown): void {
this._array.push(item); this._array.push(item);
if (this._array.length > this._limit) this._array.shift(); if (this._array.length > this._limit) this._array.shift();
} }
@ -26,7 +26,7 @@ export class limitedArray {
* Return the items within the array * Return the items within the array
* @returns {[]} * @returns {[]}
*/ */
get(): any[] { get(): unknown[] {
return this._array; return this._array;
} }
@ -51,7 +51,7 @@ export class limitedArray {
* Bulk add an array to the array * Bulk add an array to the array
* @param items * @param items
*/ */
add(items: any[]): void { add(items: unknown[]): void {
this._array = this._array.concat(items); this._array = this._array.concat(items);
if (this._array.length > this._limit) this._array = this._array.slice(this._array.length - this._limit); if (this._array.length > this._limit) this._array = this._array.slice(this._array.length - this._limit);
@ -61,7 +61,7 @@ export class limitedArray {
* Remove an item from the beginning of an array * Remove an item from the beginning of an array
* @returns {*} * @returns {*}
*/ */
shift(): any { shift(): unknown {
return this._array.shift(); return this._array.shift();
} }
} }

View File

@ -7,7 +7,7 @@
* U.once(fn) * U.once(fn)
*/ */
export function once(fn: Function): Function { export function once(fn: Function): Function {
let alreadyCalled: boolean = false; let alreadyCalled = false;
let result: Function; let result: Function;
return function (...args: any): any { return function (...args: any): any {

View File

@ -8,7 +8,7 @@
* @example * @example
* U.partOfDay('13:00') // => 'Afternoon' * U.partOfDay('13:00') // => 'Afternoon'
*/ */
export function partOfDay(timeString: string, today: boolean = false): string { export function partOfDay(timeString: string, today = false): string {
if (timeString === undefined || timeString === null) timeString = new Date().getHours().toString(); if (timeString === undefined || timeString === null) timeString = new Date().getHours().toString();
if (today === undefined) today = false; if (today === undefined) today = false;

View File

@ -8,7 +8,7 @@
* U.throttle(callback, limit) * U.throttle(callback, limit)
*/ */
export function throttle(callback: Function, limit: number): Function { export function throttle(callback: Function, limit: number): Function {
var wait: boolean = false; let wait = false;
return function (...args: any): any { return function (...args: any): any {
if (!wait) { if (!wait) {

View File

@ -0,0 +1,65 @@
import { timeToMilliseconds } from './timeToMilliseconds';
describe('Should convert strings into milliseconds', () => {
describe('Handle individual strings', () => {
test('Should handle seconds', () => {
expect(timeToMilliseconds('1s')).toEqual(1000);
expect(timeToMilliseconds('1sec')).toEqual(1000);
expect(timeToMilliseconds('1 second')).toEqual(1000);
});
test('Should handle minutes', () => {
expect(timeToMilliseconds('1m')).toEqual(60000);
expect(timeToMilliseconds('1min')).toEqual(60000);
expect(timeToMilliseconds('1 minutes')).toEqual(60000);
});
test('Should handle hours', () => {
expect(timeToMilliseconds('1h')).toEqual(3600000);
expect(timeToMilliseconds('1 hours')).toEqual(3600000);
});
test('Should handle days', () => {
expect(timeToMilliseconds('1d')).toEqual(86400000);
expect(timeToMilliseconds('1 days')).toEqual(86400000);
});
test('Should handle weeks', () => {
expect(timeToMilliseconds('1w')).toEqual(604800000);
expect(timeToMilliseconds('1 weeks')).toEqual(604800000);
});
test('Should handle years', () => {
expect(timeToMilliseconds('1y')).toEqual(31557600000);
expect(timeToMilliseconds('1 years')).toEqual(31557600000);
});
});
describe('Handle complex strings', () => {
test('Should handle 5y2w30d14h30m10s', () => {
expect(timeToMilliseconds('5y2w30d14h30m10s')).toEqual(161641810000);
});
test('1 hour and 5 seconds', () => {
expect(timeToMilliseconds('1 hour and 5 seconds')).toEqual(3605000);
});
});
describe('Handle complex strings', () => {
test('Should handle empty', () => {
expect(timeToMilliseconds('')).toEqual(0);
});
});
});

View File

@ -0,0 +1,44 @@
/**
* perform the regEx to number conversion
* @param reg
* @param timeCheck
*/
function doRegEx(reg : RegExp, timeCheck: string) : number {
if (!timeCheck || timeCheck.length === 0) return 0;
const result = reg.exec(timeCheck);
if (result && result.length > 0)
return parseInt(result[1], 10);
else return 0;
}
/**
* Get milliseconds from a string of time sections
* @param inTime *
* @signature
* U.timeToMilliseconds(inTime)
* @example
* U.timeToMilliseconds('1s') // => 1000
* U.timeToMilliseconds('1min') // => 60000
* U.timeToMilliseconds('1 weeks') // => 604800000
* U.timeToMilliseconds('5y2w30d14h30m10s') // => 161641810000
* U.timeToMilliseconds('1 hour and 5 seconds') // => 3605000
*/
export function timeToMilliseconds(inTime = '') : number {
const workTime = inTime || '';
const years = doRegEx(/(\d+)(?:\s*(?:year[s]?|y))+/gi, workTime) * 31557600000;
const weeks = doRegEx(/(\d+)(?:\s*(?:week[s]?|w))+/gi, workTime) * 604800000;
const days = doRegEx(/(\d+)(?:\s*(?:day[s]?|d))+/gi, workTime) * 86400000;
const hours = doRegEx(/(\d+)(?:\s*(?:hour[s]?|h))+/gi, workTime) * 3600000;
const minutes = doRegEx(/(\d+)(?:\s*(?:minutes[s]?|min[s]?|m))+/gi, workTime) * 60000;
const seconds = doRegEx(/(\d+)(?:\s*(?:second[s]?|sec[s]?|s))+/gi, workTime) * 1000;
return years + weeks + days + hours + minutes + seconds;
}

View File

@ -9,6 +9,6 @@
* @example * @example
* U.toHour('13:00') // => 1605532173 * U.toHour('13:00') // => 1605532173
*/ */
export function toHour(currentTimsestamp: number, extra: number = 0): number { export function toHour(currentTimsestamp: number, extra = 0): number {
return 3600000 - (currentTimsestamp % 3600000) + extra; return 3600000 - (currentTimsestamp % 3600000) + extra;
} }