Compare commits

..

No commits in common. "master" and "v3.0.11" have entirely different histories.

34 changed files with 2080 additions and 11280 deletions

View File

@ -1,66 +0,0 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -1,124 +0,0 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

4
.gitignore vendored
View File

@ -15,6 +15,8 @@ node_modules/
# builds
dist/
dist_*/
dist_web/
dist_serve/
dist_ts_web/
# custom

117
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,117 @@
# gitzone ci_default
image: hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- docker
- notpriv
snyk:
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- docker
- notpriv
# ====================
# test stage
# ====================
testLTS:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
script:
- npmci command npm install -g tslint typescript
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

11
.vscode/launch.json vendored
View File

@ -1,11 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored
View File

@ -1,26 +0,0 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,120 +0,0 @@
# Changelog
## 2024-12-14 - 4.2.0 - feat(ondemand)
Add on-demand timestamp feature
- Added an on-demand script to output human-readable time ago for current timestamp.
## 2024-12-13 - 4.1.1 - fix(smarttime.units)
Fix issue in getMilliSecondsAsHumanReadableAgoTime
- Corrected the parameter type passed to date-fns.formatDistanceToNow within getMilliSecondsAsHumanReadableAgoTime function.
## 2024-12-13 - 4.1.0 - feat(smarttime.units)
Add function to get human-readable time ago string from milliseconds.
- Introduced `getMilliSecondsAsHumanReadableAgoTime` to convert a timestamp to a human-readable text indicating time ago.
## 2024-12-13 - 4.0.9 - fix(dependencies)
Updated dependencies in package.json and resolved cron function issues.
- Updated multiple dependencies in package.json to their latest versions.
- Fixed issue in cron job instantiation by correcting the import and initialization of the croner.Cron class.
## 2024-06-23 - 4.0.8 - fix(documentation)
Corrected formatting issues in changelog.md
- Fixed markdown formatting by removing unnecessary newlines.
## 2024-06-23 - 4.0.7 - fix(build)
Remove GitLab CI configuration and update dependencies in package.json
- Removed .gitlab-ci.yml from the project
- Updated @git.zone/tsbuild from ^2.1.72 to ^2.1.80
- Updated @git.zone/tstest from ^1.0.86 to ^1.0.90
- Updated @push.rocks/tapbundle from ^5.0.15 to ^5.0.23
- Updated @types/node from ^20.11.19 to ^20.14.8
- Updated @push.rocks/lik from ^6.0.12 to ^6.0.15
- Updated dayjs from ^1.11.10 to ^1.11.11
- Fixed test files to export default tap.start()
## 2024-05-29 - 4.0.6 - Maintenance Updates
Updates to configuration files and metadata.
- Updated description in the project documentation.
- Revised tsconfig settings.
- Changes to npmextra.json regarding githost configuration.
## 2023-10-20 - 4.0.5 to 4.0.6 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2023-08-13 - 4.0.4 to 4.0.5 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2023-07-21 - 4.0.2 to 4.0.4 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2023-01-06 - 4.0.0 to 4.0.1 - Core Changes
Routine fixes and core updates.
- fix(core): update
## 2022-11-21 - 3.0.45 to 4.0.0 - Major Release
Significant changes and breaking updates.
- BREAKING CHANGE(core): switch to esm
## 2021-11-08 - 3.0.41 to 3.0.42 - Timestamp Update
Updates and bug fixes for the timestamp feature.
- fix(timestamp): add missing .isOlderThanOtherTimeStamp() to TimeStamp class
- fix(readme): fix readme
- fix(update croner): update croner package, closes #1. Thank you @Hexagon4
## 2020-09-04 - 3.0.28 to 3.0.31 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2020-07-11 - 3.0.19 to 3.0.20 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2020-05-25 - 3.0.12 to 3.0.16 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2019-06-18 - 3.0.8 to 3.0.12 - Maintenance Fixes
Routine fixes and updates.
- fix(core): update
## 2018-10-21 - 3.0.0 to 3.0.1 - Date Handling
Updates to date and time support.
- fix(date): now supports date and time
- fix(ExtendedDate): now respects single digit dates
## 2018-10-17 - 2.0.2 to 3.0.0 - Major Release
Breaking changes and dependency updates.
- BREAKING CHANGE(deps): remove moment and use luxon
## 2018-06-10 - 2.0.0 to 2.0.1 - Core Changes
Updated and changed the scope of core functionalities.
- fix(core): update and change scope
## 2017-08-16 - 1.0.0 to 1.0.3 - Initial Implementation
Inception of project with core functionalities.
- first implementation

21
license
View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Lossless GmbH (hello@lossless.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -4,26 +4,13 @@
"npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"githost": "gitlab.com",
"gitscope": "pushrocks",
"gitrepo": "smarttime",
"description": "Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.",
"npmPackagename": "@push.rocks/smarttime",
"license": "MIT",
"keywords": [
"time handling",
"cron jobs",
"timestamps",
"time intervals",
"date operations",
"time formatting",
"scheduling"
]
"shortDescription": "handle time in smart ways",
"npmPackagename": "@pushrocks/smarttime",
"license": "MIT"
}
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}

1775
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,63 +1,40 @@
{
"name": "@push.rocks/smarttime",
"name": "@pushrocks/smarttime",
"private": false,
"version": "4.2.0",
"description": "Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"version": "3.0.11",
"description": "handle time in smart ways",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest ./test)",
"build": "(tsbuild --web && tsbundle npm)",
"buildDocs": "tsdoc"
"test": "(tstest ./test/)",
"build": "(tsbuild)"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.2.0",
"@git.zone/tsbundle": "^2.1.0",
"@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.0.90",
"@push.rocks/tapbundle": "^5.5.3",
"@types/node": "^22.10.2"
"@gitzone/tsbuild": "^2.1.11",
"@gitzone/tsrun": "^1.2.6",
"@gitzone/tstest": "^1.0.24",
"@pushrocks/tapbundle": "^3.0.9",
"@types/node": "^12.0.8",
"tslint": "^5.17.0",
"tslint-config-prettier": "^1.18.0"
},
"dependencies": {
"@push.rocks/lik": "^6.1.0",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartpromise": "^4.0.4",
"croner": "^9.0.0",
"date-fns": "^4.1.0",
"dayjs": "^1.11.13",
"is-nan": "^1.3.2",
"pretty-ms": "^9.2.0"
"@pushrocks/smartpromise": "^3.0.2",
"@types/cron": "^1.7.1",
"@types/luxon": "^1.15.1",
"cron": "^1.7.1",
"luxon": "^1.16.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"ts/*",
"ts_web/*",
"dist/*",
"dist_web/*",
"assets/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
],
"type": "module",
"keywords": [
"time handling",
"cron jobs",
"timestamps",
"time intervals",
"date operations",
"time formatting",
"scheduling"
],
"homepage": "https://code.foss.global/push.rocks/smarttime",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smarttime.git"
}
]
}

10237
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@

163
readme.md
View File

@ -1,147 +1,50 @@
# @push.rocks/smarttime
# @pushrocks/smarttime
handle time in smart ways
## Install
To install `@push.rocks/smarttime`, use the following npm command:
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smarttime)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smarttime)
* [github.com (source mirror)](https://github.com/pushrocks/smarttime)
* [docs (typedoc)](https://pushrocks.gitlab.io/smarttime/)
```bash
npm install @push.rocks/smarttime --save
```
This will add `@push.rocks/smarttime` to your project's dependencies.
## Status for master
[![build status](https://gitlab.com/pushrocks/smarttime/badges/master/build.svg)](https://gitlab.com/pushrocks/smarttime/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smarttime/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smarttime/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smarttime.svg)](https://www.npmjs.com/package/@pushrocks/smarttime)
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smarttime/badge.svg)](https://snyk.io/test/npm/@pushrocks/smarttime)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
## Usage
`@push.rocks/smarttime` provides a comprehensive toolkit for handling various aspects of time manipulation, scheduling, and comparison in a TypeScript project. The following sections will guide you through the capabilities of this package, showcasing how to use its classes and functions effectively.
Use TypeScript for best in class instellisense.
### Handling Time Units and Calculations
Smarttime offers smart ways to deal with time.
#### Working with Units
```typescript
import { units, getMilliSecondsFromUnits } from '@push.rocks/smarttime';
// Define a duration using a combination of time units
let durationInMilliseconds = getMilliSecondsFromUnits({
years: 1,
months: 2,
weeks: 3,
days: 4,
hours: 5,
minutes: 6,
seconds: 7
});
console.log(`Duration in milliseconds: ${durationInMilliseconds}`);
```
In the example above, we specify a complex duration made up of various time units using the `getMilliSecondsFromUnits` function. This is quite useful for calculations where you need to define durations in a more human-readable format.
### Scheduling with CronManager
`@push.rocks/smarttime` includes a powerful scheduling tool called `CronManager`, which allows you to schedule tasks using cron syntax.
#### Creating and Starting a CronManager
```typescript
import { CronManager } from '@push.rocks/smarttime';
const cronManager = new CronManager();
// Adding a cron job that runs every minute
cronManager.addCronjob('* * * * *', async () => {
console.log('This task runs every minute.');
});
// Starting the CronManager
cronManager.start();
```
The example demonstrates how to create a `CronManager`, add a cron job that runs every minute, and start the scheduling. You can add multiple cron jobs to a single manager, each with its own scheduling and task.
### Working with Extended Date Class
The `ExtendedDate` class extends the native JavaScript `Date` object, providing additional functionality for handling dates in various formats and zones.
#### Creating ExtendedDate Instances
```typescript
import { ExtendedDate } from '@push.rocks/smarttime';
// Creating a date from a European format string
const dateFromEuroString = ExtendedDate.fromEuropeanDate('31.12.2023');
console.log(dateFromEuroString.toString());
// Creating a date from a hyphed date string
const dateFromHyphedString = ExtendedDate.fromHyphedDate('2023-12-31');
console.log(dateFromHyphedString.toString());
```
#### Checking if a Date is Today
```typescript
import { ExtendedDate } from '@push.rocks/smarttime';
const someDate = new ExtendedDate();
console.log(`Is someDate today? ${someDate.isToday()}`);
```
Using `ExtendedDate`, you can also easily check if a given date is today. This simplifies certain date comparisons that are common in web and application development.
### High-Resolution Time Measurement
For performance testing and high-resolution time tracking, `@push.rocks/smarttime` provides the `HrtMeasurement` class.
### class CronManager
This class provides scheduling of functions with a cron syntax
```typescript
import { HrtMeasurement } from '@push.rocks/smarttime';
const hrtMeasurement = new HrtMeasurement();
hrtMeasurement.start();
// Simulate some operations...
setTimeout(() => {
hrtMeasurement.stop();
console.log(`Operation took ${hrtMeasurement.milliSeconds} milliseconds.`);
}, 1000);
import { CronManager } from '@pushrocks/smarrtime';
const cronManagerInstance = new CronManager();
cronManagerInstance.addConrjob('* * * * * *', async () => {
console.log('hello'); // will log 'hello' to console once every second;
})
cronManagerInstance.start();
```
This class allows you to measure the duration of operations in your code with high precision, offering both milliseconds and nanoseconds resolutions.
### class ExtendedDate
This class offers static functions to create zone specific JavaScript dates from European formated time strings.
### Interval and Timer functionalities
`@push.rocks/smarttime` includes classes for managing intervals and timers with enhanced control, such as pause, resume, and reset capabilities.
#### Using the Timer class
```typescript
import { Timer } from '@push.rocks/smarttime';
const timer = new Timer(5000); // A 5-second timer
timer.start();
timer.completed.then(() => {
console.log('Timer completed!');
});
// Resetting the timer
timer.reset();
timer.start();
```TypeScript
import { ExtendedDate } from '@pushrocks/smarttime'
const myDate: Date = ExtendedDate.fromEuropeanDate('8.6.2018')
```
The `Timer` class allows for asynchronous waiting in a more object-oriented manner. In the example, a `Timer` is created for five seconds, started, and then reset for demonstration purposes.
For further information read the linked docs at the top of this readme.
### Conclusion
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
`@push.rocks/smarttime` offers an extensive toolkit for dealing with time in JavaScript and TypeScript applications. Whether you need precise timing, scheduled tasks, or extended date functionalities, this package provides a suite of tools designed to handle time in smart and efficient ways. The examples provided herein demonstrate the core functionalities, aiming to help you integrate time-related features into your projects with ease.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
[![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://maintainedby.lossless.com)

View File

@ -1,3 +0,0 @@
import * as smarttime from '../ts/index.js';
console.log(smarttime.getMilliSecondsAsHumanReadableAgoTime(Date.now()));

View File

@ -1,60 +0,0 @@
import { tap, expect } from '@push.rocks/tapbundle';
import * as smarttime from '../ts/index.js';
let testCronManager: smarttime.CronManager;
tap.test('should create a valid instance of cronmanager', async () => {
testCronManager = new smarttime.CronManager();
expect(testCronManager).toBeInstanceOf(smarttime.CronManager);
});
tap.test('should create a valid cronJon', async (tools) => {
const done = tools.defer();
const done2 = tools.defer();
const done3 = tools.defer();
let counter = 0;
let counter2 = 0;
let counter3 = 0;
const cronJob = testCronManager.addCronjob('*/2 * * * * *', async () => {
if (counter === 5) {
testCronManager.removeCronjob(cronJob);
done.resolve();
}
counter++;
console.log(`${new Date().getSeconds()} hey ${counter} -> runs every 2 seconds`);
});
const cronJob2 = testCronManager.addCronjob('*/3 * * * * *', async () => {
if (counter2 === 5) {
testCronManager.removeCronjob(cronJob2);
done2.resolve();
}
counter2++;
console.log(`${new Date().getSeconds()} hey ${counter2} -> runs every 3 seconds`);
});
const cronJob3 = testCronManager.addCronjob('*/4 * * * * *', async () => {
if (counter3 === 5) {
done3.resolve();
}
counter3++;
console.log(`${new Date().getSeconds()} hey ${counter3} -> runs every 4 seconds`);
});
testCronManager.start();
await done.promise;
await done2.promise;
await done3.promise;
testCronManager.stop();
testCronManager.removeCronjob(cronJob3);
});
tap.test('runs every full minute', async (tools) => {
const done = tools.defer();
const cronJob = testCronManager.addCronjob('0 * * * * *', async () => {
done.resolve();
});
testCronManager.start();
await done.promise;
testCronManager.stop();
});
export default tap.start();

27
test/test.cronmanager.ts Normal file
View File

@ -0,0 +1,27 @@
import { tap, expect } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index';
let testCronManager: smarttime.CronManager;
tap.test('should create a valid instance of cronmanager', async () => {
testCronManager = new smarttime.CronManager();
expect(testCronManager).to.be.instanceOf(smarttime.CronManager);
});
tap.test('should create a valid cronJon', async tools => {
const done = tools.defer();
let counter = 0;
testCronManager.addCronjob('* * * * * *', () => {
if (counter === 10) {
done.resolve();
}
counter++;
console.log(`hey ${counter}`);
});
testCronManager.start();
await done.promise;
testCronManager.stop();
});
tap.start();

View File

@ -1,11 +1,6 @@
import { expect, tap } from '@push.rocks/tapbundle';
import { expect, tap } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index.js';
tap.test('should create a valid JavaScript Date', async () => {
const extendedDate = new smarttime.ExtendedDate(Date.now());
console.log(extendedDate);
});
import * as smarttime from '../ts/index';
tap.test('should create a valid JavaScript Date from European TimeStamp', async () => {
const extendedDate = smarttime.ExtendedDate.fromEuropeanDate('1.6.2018');
@ -23,12 +18,7 @@ tap.test('should create a date and time with European Format', async () => {
tap.test('should create a European date string', async () => {
const extendedDate = smarttime.ExtendedDate.fromHyphedDate('2018-02-13');
expect(extendedDate.exportToEuropeanDate()).toEqual('13.02.2018');
expect(extendedDate.exportToEuropeanDate()).to.equal('13.02.2018');
});
tap.test('should format a date', async () => {
const extendedDate = new smarttime.ExtendedDate(Date.now());
console.log(extendedDate.format('YYYY-MM-DD - hh:mm'));
});
export default tap.start();
tap.start();

View File

@ -1,13 +1,13 @@
// tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from '@push.rocks/tapbundle';
import { expect, tap } from '@pushrocks/tapbundle';
import { Timer } from '../ts/index.js';
import { Timer } from '../ts/index';
let testTimer: Timer;
tap.test('should create a valid timer', async () => {
testTimer = new Timer(1000);
expect(testTimer).toBeInstanceOf(Timer);
expect(testTimer).to.be.instanceof(Timer);
});
tap.test('should start timer', async () => {
@ -23,4 +23,4 @@ tap.test('should reset a timer', async () => {
await testTimer.completed;
});
export default tap.start();
tap.start();

View File

@ -1,35 +1,35 @@
// tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from '@push.rocks/tapbundle';
import * as smarttime from '../ts/index.js';
import { expect, tap } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index';
// Test TimeStamp class
let testTimeStamp: smarttime.TimeStamp;
let testTimeStamp2: smarttime.TimeStamp;
tap.test('should create valid testTimeStamp instance', async (tools) => {
tap.test('should create valid testTimeStamp instance', async tools => {
testTimeStamp = new smarttime.TimeStamp();
await tools.delayFor(2);
testTimeStamp2 = new smarttime.TimeStamp();
expect(testTimeStamp).toBeInstanceOf(smarttime.TimeStamp);
expect(testTimeStamp).toBeInstanceOf(smarttime.TimeStamp);
expect(testTimeStamp).to.be.instanceof(smarttime.TimeStamp);
expect(testTimeStamp).to.be.instanceof(smarttime.TimeStamp);
});
tap.test('should have valid linuxtime', async () => {
// tslint:disable-next-line:no-unused-expression
expect(testTimeStamp.isOlderThan(testTimeStamp2)).toBeTrue();
expect(testTimeStamp.isOlderThan(testTimeStamp2)).to.be.true;
// tslint:disable-next-line:no-unused-expression
expect(testTimeStamp.isYoungerThanOtherTimeStamp(testTimeStamp2)).toBeFalse();
expect(testTimeStamp.isYoungerThanOtherTimeStamp(testTimeStamp2)).to.be.false;
});
let testHrtMeasurement: smarttime.HrtMeasurement;
// Test HrtMeasurement
tap.test('should create valid HrtMeasurements', async (tools) => {
tap.test('should create valid HrtMeasurements', async tools => {
testHrtMeasurement = new smarttime.HrtMeasurement();
testHrtMeasurement.start();
await tools.delayFor(20);
testHrtMeasurement.stop();
expect(testHrtMeasurement.milliSeconds).toBeGreaterThan(19);
expect(testHrtMeasurement.milliSeconds).toBeLessThan(25);
expect(testHrtMeasurement.milliSeconds).to.be.greaterThan(19);
expect(testHrtMeasurement.milliSeconds).to.be.lessThan(25);
});
// check units
@ -41,10 +41,10 @@ tap.test('should combine units', async () => {
weeks: 2,
days: 2,
hours: 2,
minutes: 2,
minutes: 2
});
// tslint:disable-next-line:no-console
console.log(computedTime);
});
export default tap.start();
tap.start();

View File

@ -1,8 +0,0 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smarttime',
version: '4.2.0',
description: 'Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.'
}

View File

@ -1,8 +1,10 @@
export * from './smarttime.classes.cronmanager.js';
export * from './smarttime.classes.cronjob.js';
export * from './smarttime.classes.extendeddate.js';
export * from './smarttime.classes.hrtmeasurement.js';
export * from './smarttime.classes.interval.js';
export * from './smarttime.classes.timer.js';
export * from './smarttime.classes.timestamp.js';
export * from './smarttime.units.js';
import * as plugins from './smarttime.plugins';
export * from './smarttime.classes.cronmanager';
export * from './smarttime.classes.extendeddate';
export * from './smarttime.classes.hrtmeasurement';
export * from './smarttime.classes.timer';
export * from './smarttime.classes.timestamp';
export * from './smarttime.units';
export { luxon } from './smarttime.plugins';

View File

@ -1,58 +0,0 @@
import * as plugins from './smarttime.plugins.js';
import { CronManager } from './smarttime.classes.cronmanager.js';
import { CronParser } from './smarttime.classes.cronparser.js';
export type TJobFunction =
| ((triggerTimeArg?: number) => void)
| ((triggerTimeArg?: number) => Promise<any>);
export class CronJob {
public cronParser: plugins.croner.Cron;
public status: 'started' | 'stopped' | 'initial' = 'initial';
public cronExpression: string;
public jobFunction: TJobFunction;
private nextExecutionUnix: number = 0;
constructor(cronManager: CronManager, cronExpressionArg: string, jobFunction: TJobFunction) {
this.cronExpression = cronExpressionArg;
this.jobFunction = jobFunction;
this.cronParser = new plugins.croner.Cron(cronExpressionArg);
}
/**
* checks wether the cronjob needs to be executed
*/
public checkExecution(): number {
if (this.nextExecutionUnix === 0) {
this.getNextExecutionTime();
}
if (Date.now() > this.nextExecutionUnix) {
const maybePromise = this.jobFunction(this.nextExecutionUnix);
if (maybePromise instanceof Promise) {
maybePromise.catch((e) => console.log(e));
}
this.nextExecutionUnix = this.getNextExecutionTime();
}
return this.nextExecutionUnix;
}
public getNextExecutionTime() {
return (this.nextExecutionUnix = Date.now() + this.getTimeToNextExecution());
}
/**
* gets the time to next execution
*/
public getTimeToNextExecution() {
return this.cronParser.msToNext();
}
public start() {
this.status = 'started';
}
public stop() {
this.status = 'stopped';
}
}

View File

@ -1,85 +1,34 @@
import * as plugins from './smarttime.plugins.js';
import { CronJob, type TJobFunction } from './smarttime.classes.cronjob.js';
import { getMilliSecondsAsHumanReadableString } from './smarttime.units.js';
import * as plugins from './smarttime.plugins';
export class CronManager {
public executionTimeout: plugins.smartdelay.Timeout<void>;
public status: 'started' | 'stopped' = 'stopped';
public cronjobs = new plugins.lik.ObjectMap<CronJob>();
constructor() {}
public cronjobs: plugins.cron.CronJob[] = [];
public addCronjob(cronIdentifierArg: string, cronFunctionArg: TJobFunction) {
const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg);
this.cronjobs.add(newCronJob);
public addCronjob(cronIdentifierArg: string, cronFunctionArg: plugins.cron.CronCommand) {
const newCronJob = new plugins.cron.CronJob(cronIdentifierArg, cronFunctionArg);
if (this.status === 'started') {
newCronJob.start();
}
return newCronJob;
}
public removeCronjob(cronjobArg: CronJob) {
cronjobArg.stop();
this.cronjobs.remove(cronjobArg);
this.cronjobs.push(newCronJob);
}
/**
* starts the cronjob
*/
public start() {
if (this.status !== 'started') {
this.status = 'started';
for (const cronJob of this.cronjobs.getArray()) {
cronJob.start();
}
this.runCronCycle();
this.status = 'started';
for (const cron of this.cronjobs) {
cron.start();
}
}
private async runCronCycle() {
this.executionTimeout = new plugins.smartdelay.Timeout(0);
do {
let nextRunningCronjob: CronJob;
for (const cronJob of this.cronjobs.getArray()) {
cronJob.checkExecution();
if (
!nextRunningCronjob ||
cronJob.getTimeToNextExecution() < nextRunningCronjob.getTimeToNextExecution()
) {
nextRunningCronjob = cronJob;
}
}
if (nextRunningCronjob) {
this.executionTimeout = new plugins.smartdelay.Timeout(
nextRunningCronjob.getTimeToNextExecution()
);
console.log(
`Next CronJob scheduled in ${getMilliSecondsAsHumanReadableString(
this.executionTimeout.getTimeLeft()
)}`
);
} else {
this.executionTimeout = new plugins.smartdelay.Timeout(1000);
console.log('no cronjobs specified! Checking again in 1 second');
}
await this.executionTimeout.promise;
} while (this.status === 'started');
};
/**
* stops all cronjobs
*/
public stop() {
if (this.status === 'started') {
this.status = 'stopped';
this.executionTimeout.cancel();
} else {
console.log(`You tried to stop a CronManager that was not actually started.`);
}
for (const cron of this.cronjobs.getArray()) {
this.status = 'stopped';
for (const cron of this.cronjobs) {
cron.stop();
}
}

View File

@ -1,88 +0,0 @@
import * as plugins from './smarttime.plugins.js';
export class CronParser {
public cronExpression: string;
public get cronArray() {
return this.cronExpression.split(' ');
}
constructor(cronExpressionArg: string) {
this.cronExpression = cronExpressionArg;
if (this.cronArray.length < 6) {
throw new Error('CronParser needs second level accuracy');
}
}
private getNextPartMatch(cronPart: string, startValue: number, moduloArg: number) {
if (cronPart === '*') {
return startValue;
}
if (cronPart.includes('/')) {
const every = parseInt(cronPart.split('/')[1], 10);
const findEvenMatch = (recursionStartArg: number): number => {
if (recursionStartArg % every === 0) {
return recursionStartArg;
} else {
return findEvenMatch(recursionStartArg + 1);
}
};
return findEvenMatch(startValue);
}
if (parseInt(cronPart, 10) || cronPart === '0') {
const match = parseInt(cronPart, 10);
return match;
}
}
public msToNext() {
const cronArray = this.cronArray;
const secondExpression = cronArray[0];
const minuteExpression = cronArray[1];
const hourExpression = cronArray[2];
const dayExpression = cronArray[3];
const monthExpression = cronArray[4];
const yearExpression = cronArray[5];
let currentDate = new Date();
let currentSecond = currentDate.getSeconds() + 1;
let currentMinute = currentDate.getMinutes();
let currentHour = currentDate.getHours();
let currentDay = currentDate.getDate();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
const targetSecond = this.getNextPartMatch(secondExpression, currentSecond, 59);
if (targetSecond < currentSecond) {
currentMinute = (currentMinute + 1) % 59;
}
const targetMinute = this.getNextPartMatch(minuteExpression, currentMinute, 59);
if (targetMinute < currentMinute) {
currentHour = (currentHour + 1) % 23;
}
const targetHour = this.getNextPartMatch(hourExpression, currentHour, 23);
if (targetHour < currentHour) {
currentDay = (currentDay + 1) % 30;
}
const targetDay = currentDay;
if (targetDay < currentDay) {
currentMonth = (currentMonth + 1) % 11;
}
const targetMonth = currentMonth;
if (targetMonth < currentMonth) {
currentYear = currentYear + 1;
}
const targetYear = currentYear;
const targetDate = new Date(
targetYear,
targetMonth,
targetDay,
targetHour,
targetMinute,
targetSecond
);
const targetTime = targetDate.getTime();
return targetTime - Date.now();
}
}

View File

@ -1,5 +1,4 @@
import * as plugins from './smarttime.plugins.js';
import * as units from './smarttime.units.js';
import * as plugins from './smarttime.plugins';
export type TAvailableZone = 'Europe/Berlin';
@ -21,18 +20,14 @@ export class ExtendedDate extends Date {
return new ExtendedDate(milliSeconds);
}
public static fromDate(dateArg: Date) {
return new ExtendedDate(dateArg.getTime());
}
public static fromEuropeanDate(europeanDate: string) {
const dateArray = /(.*)\.(.*)\.(.*)/.exec(europeanDate);
const date = new Date(
const luxonDate = plugins.luxon.DateTime.utc(
parseFloat(dateArray[3]), // year
parseFloat(dateArray[2]) - 1, // month
parseFloat(dateArray[2]), // month
parseFloat(dateArray[1]) // day
);
const unixMilli = date.getTime();
const unixMilli = luxonDate.toMillis();
return new ExtendedDate(unixMilli);
}
@ -65,15 +60,15 @@ export class ExtendedDate extends Date {
const dateTimeString = `${dateArray[3]}-${sliceDate(dateArray[2])}-${sliceDate(
dateArray[1]
)}T${timeArg}`;
const date = plugins.dayjs(dateTimeString);
const unixMilli = date.toDate().getTime();
const luxonDate = plugins.luxon.DateTime.fromISO(dateTimeString, {
zone: zoneArg
});
const unixMilli = luxonDate.toMillis();
return new ExtendedDate(unixMilli);
}
// INSTANCE
public timezone: TAvailableZone;
constructor(unixMilli: number = Date.now()) {
constructor(unixMilli: number) {
super(unixMilli);
}
@ -83,11 +78,6 @@ export class ExtendedDate extends Date {
return `${units.dayString}.${units.monthString}.${units.yearString}`;
}
public exportToHyphedSortableDate() {
const units = this.exportToUnits();
return `${units.yearString}-${units.monthString}-${units.dayString}`;
}
/**
* exports units
*/
@ -104,7 +94,7 @@ export class ExtendedDate extends Date {
'September',
'October',
'November',
'December',
'December'
];
const daysArray = [
'Monday',
@ -113,39 +103,18 @@ export class ExtendedDate extends Date {
'Thursday',
'Friday',
'Saturday',
'Sunday',
'Sunday'
];
return {
year: this.getFullYear(),
yearString: `${this.getFullYear()}`,
month: this.getMonth() + 1,
monthString: ('0' + (this.getMonth() + 1)).slice(-2),
monthString: ("0" + (this.getMonth() + 1)).slice(-2),
monthName: monthsArray[this.getMonth()],
day: this.getDate(),
dayString: ('0' + this.getDate()).slice(-2),
dayString: ("0" + this.getDate()).slice(-2),
dayOfTheWeek: this.getDay(),
dayOfTheWeekName: daysArray[this.getDay()],
dayOfTheWeekName: daysArray[this.getDay()]
};
}
public format(formatArg: string) {
return plugins.dayjs(this.getTime()).format(formatArg);
}
/**
* boolean checks
*/
public isToday() {
return plugins.dayjs(this.getTime()).isToday();
}
public lessTimePassedToNow(unitArgs: units.IUnitCombinationArg): boolean {
const maxPassedUnixTime = units.getMilliSecondsFromUnits(unitArgs);
const actualPassedUnixTime = Date.now() - this.getTime();
return actualPassedUnixTime < maxPassedUnixTime;
}
public moreTimePassedToNow(unitArgs: units.IUnitCombinationArg) {
return !this.lessTimePassedToNow(unitArgs);
}
}

View File

@ -1,11 +1,13 @@
import * as process from 'process';
/**
* easy high resolution time measurement
*/
export class HrtMeasurement {
public nanoSeconds: number = null;
public milliSeconds: number = null;
private _milliStart: number = null;
private _milliDiff: number = null;
private _hrTimeStart = null;
private _hrTimeStopDiff = null;
private _started: boolean = false;
/**
@ -13,7 +15,7 @@ export class HrtMeasurement {
*/
public start() {
this._started = true;
this._milliStart = Date.now();
this._hrTimeStart = process.hrtime();
}
/**
@ -24,9 +26,9 @@ export class HrtMeasurement {
console.log("Hasn't started yet");
return;
}
this._milliDiff = Date.now() - this._milliStart;
this.nanoSeconds = this._milliDiff * 1000;
this.milliSeconds = this._milliDiff;
this._hrTimeStopDiff = process.hrtime(this._hrTimeStart);
this.nanoSeconds = this._hrTimeStopDiff[0] * 1e9 + this._hrTimeStopDiff[1];
this.milliSeconds = this.nanoSeconds / 1000000;
return this;
}
@ -36,8 +38,8 @@ export class HrtMeasurement {
public reset() {
this.nanoSeconds = null;
this.milliSeconds = null;
this._milliStart = null;
this._milliDiff = null;
this._hrTimeStart = null;
this._hrTimeStopDiff = null;
this._started = false;
}
}

View File

@ -1,43 +0,0 @@
import * as plugins from './smarttime.plugins.js';
export class Interval {
public status: 'started' | 'stopped' | 'initial' = 'initial';
private statusAuthorization: any = null;
// timings
public intervalMilliseconds: number;
public nextIntervalMillisenconds: number;
public intervalJobs: Array<() => any> = [];
constructor(intervalMillisencondsArg: number) {
this.intervalMilliseconds = intervalMillisencondsArg;
}
public start() {
this.status = 'started';
const statusAuth = new Date();
this.statusAuthorization = statusAuth;
const runInterval = async () => {
while (this.status === 'started' && this.statusAuthorization === statusAuth) {
await plugins.smartdelay.delayFor(this.intervalMilliseconds);
this.executeIntervalJobs();
}
};
runInterval();
}
public stop() {
this.status = 'stopped';
this.statusAuthorization = null;
}
public addIntervalJob(funcArg: () => any) {
this.intervalJobs.push(funcArg);
}
private executeIntervalJobs() {
for (const funcArg of this.intervalJobs) {
funcArg();
}
}
}

View File

@ -1,6 +1,6 @@
import * as plugins from './smarttime.plugins.js';
import * as plugins from './smarttime.plugins';
import { TimeStamp } from './smarttime.classes.timestamp.js';
import { TimeStamp } from './smarttime.classes.timestamp';
export type TimerState = 'initiated' | 'started' | 'paused' | 'completed';
@ -36,7 +36,7 @@ export class Timer {
/**
* the current timeout the needs to be canceled when this Timer is stopped
*/
private currentTimeout: NodeJS.Timeout;
private currentTimeout: NodeJS.Timer;
// a deferred triggeted when Timer has completed
private completedDeferred = plugins.smartpromise.defer<void>();

View File

@ -1,4 +1,4 @@
import * as plugins from './smarttime.plugins.js';
import * as plugins from './smarttime.plugins';
/**
* TimeStamp
@ -8,7 +8,7 @@ export class TimeStamp {
/**
* returns new TimeStamp from milliseconds
*/
public static fromMilliSeconds(milliSecondsArg: number) {
public static fromMilliSeconds(milliSecondsArg) {
return new TimeStamp(milliSecondsArg);
}
@ -53,19 +53,6 @@ export class TimeStamp {
this.epochtime = Math.floor(this.milliSeconds / 1000);
}
/**
* returns a boolean for wether the timestamp is older than another timestamp
* @param TimeStampArg
* @param tresholdTimeArg
*/
public isOlderThanOtherTimeStamp(TimeStampArg: TimeStamp, tresholdTimeArg: number = 0) {
if (this.milliSeconds < TimeStampArg.milliSeconds - tresholdTimeArg) {
return true;
} else {
return false;
}
}
/**
* Is the current instance older than the argument
* @param TimeStampArg
@ -79,7 +66,7 @@ export class TimeStamp {
}
/**
* returns a boolean for wether the timestamp is younger than another timestamp
* returns a boolean for wether a timestamp is younger
* @param TimeStampArg
* @param tresholdTimeArg
*/

View File

@ -1,17 +1,10 @@
// @pushrocks scope
import * as lik from '@push.rocks/lik';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartpromise from '@push.rocks/smartpromise';
import * as smartpromise from '@pushrocks/smartpromise';
export { lik, smartdelay, smartpromise };
export { smartpromise };
// third parties;
import * as croner from 'croner';
import * as dateFns from 'date-fns';
import dayjs from 'dayjs';
import isToday from 'dayjs/plugin/isToday.js';
import prettyMs from 'pretty-ms';
// third parties
import * as luxon from 'luxon';
import * as cron from 'cron';
dayjs.extend(isToday);
export { croner, dateFns, dayjs, prettyMs };
export { luxon, cron };

View File

@ -1,5 +1,3 @@
import * as plugins from './smarttime.plugins.js';
export let units = {
years: (timesArg = 1): number => {
return timesArg * 3.154e10;
@ -18,10 +16,7 @@ export let units = {
},
minutes: (timesArg = 1) => {
return timesArg * 60000;
},
seconds: (timesArg = 1) => {
return timesArg * 1000;
},
}
};
export interface IUnitCombinationArg {
@ -31,12 +26,11 @@ export interface IUnitCombinationArg {
days?: number;
hours?: number;
minutes?: number;
seconds?: number;
}
export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => {
let timeInMilliseconds = 0;
let addMilliSeconds = (milliSecondsArg: number) => {
let addMilliSeconds = milliSecondsArg => {
timeInMilliseconds = timeInMilliseconds + milliSecondsArg;
};
if (combinationArg.years) {
@ -57,17 +51,6 @@ export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => {
if (combinationArg.minutes) {
addMilliSeconds(units.minutes(combinationArg.minutes));
}
if (combinationArg.seconds) {
addMilliSeconds(units.seconds(combinationArg.seconds));
}
return timeInMilliseconds;
};
export const getMilliSecondsAsHumanReadableString = (milliSecondsArg: number): string => {
return plugins.prettyMs(milliSecondsArg);
};
export const getMilliSecondsAsHumanReadableAgoTime = (timeStampArg: number): string => {
return plugins.dateFns.formatDistanceToNow(new Date(timeStampArg));
}

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

17
tslint.json Normal file
View File

@ -0,0 +1,17 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}