Compare commits

..

10 Commits

20 changed files with 3459 additions and 1476 deletions

83
.eslintrc.json Normal file
View File

@@ -0,0 +1,83 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier/prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
],
"curly": [
"error",
"multi-or-nest"
],
"max-len": [
"error",
{
"code": 80,
"ignoreUrls": true,
"ignoreComments": true
}
],
"no-mixed-operators": "error",
"no-tabs": [
"error",
{
"allowIndentationTabs": true
}
],
"lines-around-comment": [
"error",
{
"beforeBlockComment": true,
"afterBlockComment": true,
"beforeLineComment": true,
"afterLineComment": true,
"allowBlockStart": true,
"allowBlockEnd": true,
"allowObjectStart": true,
"allowObjectEnd": true,
"allowArrayStart": true,
"allowArrayEnd": true
}
],
"lines-between-class-members": [
"error",
"never"
],
"padding-line-between-statements": [
"error",
{
"blankLine": "always",
"prev": "*",
"next": "return"
}
]
}
}

6
.prettierrc.toml Normal file
View File

@@ -0,0 +1,6 @@
trailingComma = 'none'
tabWidth = 2
semi = false
singleQuote = true
printWidth = 80
bracketSameLine = true

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,7 +0,0 @@
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
yarnPath: .yarn/releases/yarn-3.2.0.cjs

22
LICENCE Normal file
View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright © 2022
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.

106
README.md Normal file
View File

@@ -0,0 +1,106 @@
# vikingowls-ts-snippets
## A collection of often used typescript snippets
---
### Utils
#### sleep()
The sleep function takes the time to sleep in milliseconds.
```ts
import { sleep } from "vikingowls-ts-snippets";
sleep(2000).then(any => {
// do-something
})
```
---
### Dom Utils
#### addGlobalEventListener()
The addGlobalEventListener function takes a type (string), a selector (string), a callback function, options (boolean or AddEventListenerOptions), and a parent (DOM or querySelector, etc)
```ts
import {addGlobalEventListener, qs} from "./domUtils";
addGlobalEventListener(
"click",
".btn",
() => console.log("Run once"),
{once: true}
)
addGlobalEventListener(
"click",
".btn",
() => console.log("Only works inside the wrapper class"),
{},
qs(".wrapper")
)
```
#### qs()
The qs function takes a selector (string) and a parent (DOM etc)
```ts
import {qs} from "./domUtils";
// instead of document.querySelector(".btn")
qs(".btn")
```
#### qsa()
The qsa function takes a selector (string) and a parent (DOM etc) and returns an Array of Elements
```ts
import {qsa} from "./domUtils";
// instead of document.querySelectorAll(".btn")
qsa(".btn")
```
---
### Formatters
#### formatCurrency()
The formatCurrency function takes a number and a currency (as shown).
The output defaults to the locale set in the browser but can be set manually.
```ts
import { formatCurrency } from "vikingowls-ts-snippets";
formatCurrency(9_123_456.789123, "EUR", "de-de")
// prints in germany "9.123.456,79 €"
formatCurrency(9_123_456.789123, "USD")
// prints in usa "$9,123,456.79"
```
#### formatNumber()
The formatNumber function takes a number.
The output defaults to the locale set in the browser but can be set manually.
```ts
import { formatNumber } from "vikingowls-ts-snippets";
formatNumber(9_123_456.789123, "de-de")
// prints in germany "9.123.456,789"
formatNumber(9_123_456.789123)
// prints in usa "9,123,456.789"
```
#### formatCompactNumber()
The formatCompactNumber function takes a number.
The output defaults to the locale set in the browser but can be set manually.
```ts
import { formatCompactNumber } from "vikingowls-ts-snippets";
formatCompactNumber(9_123_456.789123, "de-de")
// prints in germany "9,1 Mio."
formatCompactNumber(9_123_456.789123)
// prints in usa "9.1M"
```
#### formatRelativeDate()
The formatRelativeDate function takes a Date (end Date).
You also can set a default 'start Date'.
The output defaults to the locale set in the browser but can be set manually.
```ts
import { formatRelativeDate } from "vikingowls-ts-snippets";
formatRelativeDate(new Date().getSeconds() - 20000, new Date().getSeconds(), "de-de")
// prints in germany "vor 20 Sekunden"
formatRelativeDate(new Date().getSeconds() - 20000, new Date().getSeconds())
// prints in usa "20 seconds ago"
```

20
index.html Normal file
View File

@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="dist/index.js" type="module"></script>
</head>
<body>
<button class="tester">test</button>
<script type="module">
import {formatRelativeDate} from "./dist";
console.log(formatRelativeDate(new Date().getSeconds() - 20000, new Date().getSeconds()))
</script>
</body>
</html>

32
lib/domUtils.ts Normal file
View File

@@ -0,0 +1,32 @@
export const addGlobalEventListener = (
type: string,
selector: string,
callback: (arg0: Event) => void,
options: boolean | AddEventListenerOptions,
parent = document
): void => {
parent.addEventListener(
type,
(e: Event) => {
if (e != null && e.target != null) {
const el = e.target as Element
if (el.matches(selector)) callback(e)
}
},
options
)
}
export const qs = (
selector: string | keyof HTMLElementTagNameMap,
parent = document
): Element => {
return parent.querySelector(selector) as unknown as Element
}
export const qsa = (
selector: string | keyof HTMLElementTagNameMap,
parent = document
): NodeListOf<Element> => {
return parent.querySelectorAll(selector)
}

87
lib/formatters.ts Normal file
View File

@@ -0,0 +1,87 @@
export const formatCurrency = (
number: number,
currency: string,
locale: string | null
): string => {
const CURRENCY_FORMATTER = new Intl.NumberFormat(locale || '', {
currency: currency,
style: 'currency'
})
return CURRENCY_FORMATTER.format(number)
}
export const formatNumber = (
number: number,
locale: string | undefined = undefined
): string => {
const NUMBER_FORMATTER = new Intl.NumberFormat(locale)
return NUMBER_FORMATTER.format(number)
}
export const formatCompactNumber = (
number: number,
locale: string | undefined = undefined
): string => {
const COMPACT_NUMBER_FORMATTER = new Intl.NumberFormat(locale, {
notation: 'compact'
})
return COMPACT_NUMBER_FORMATTER.format(number)
}
type DivisionsT = {
amount: number
name:
| 'year'
| 'years'
| 'quarter'
| 'quarters'
| 'month'
| 'months'
| 'week'
| 'weeks'
| 'day'
| 'days'
| 'hour'
| 'hours'
| 'minute'
| 'minutes'
| 'second'
| 'seconds'
}
const DIVISIONS: DivisionsT[] = [
{ amount: 60, name: 'seconds' },
{ amount: 60, name: 'minutes' },
{ amount: 24, name: 'hours' },
{ amount: 7, name: 'days' },
{ amount: 4.34524, name: 'weeks' },
{ amount: 12, name: 'months' },
{ amount: Number.POSITIVE_INFINITY, name: 'years' }
]
export const formatRelativeDate = (
toDate: number,
fromDate: number = new Date().getSeconds(),
locale: string | undefined = undefined
): string => {
const RELATIVE_DATE_FORMATTER = new Intl.RelativeTimeFormat(locale, {
numeric: 'auto'
})
let duration = (toDate - fromDate) / 1000
let output = ''
for (let i = 0; i <= DIVISIONS.length; i++) {
const division = DIVISIONS[i]
if (Math.abs(duration) < division.amount) {
output = RELATIVE_DATE_FORMATTER.format(
Math.round(duration),
division.name
)
}
duration /= division.amount
}
return output
}

8
lib/index.ts Normal file
View File

@@ -0,0 +1,8 @@
export { sleep } from './utils.js'
export { qsa, qs, addGlobalEventListener } from './domUtils.js'
export {
formatCompactNumber,
formatNumber,
formatCurrency,
formatRelativeDate
} from './formatters.js'

3
lib/utils.ts Normal file
View File

@@ -0,0 +1,3 @@
export const sleep = (time: number): Promise<unknown> => {
return new Promise((resolve) => setTimeout(resolve, time))
}

3062
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,17 +1,24 @@
{
"name": "snippets-ts",
"version": "0.0.1",
"description": "Private typescript snippets library",
"main": "./dist/index.js",
"name": "vikingowls-ts-snippets",
"version": "0.0.6",
"description": "VikingOwls typescript snippets library",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"/dist"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc",
"publish": "yarn run build && npm publish",
"publish-beta": "yarn run build && npm publish --tag beta"
"publish:lib": "npm run build && npm publish",
"publish:beta": "npm run build && npm publish --tag beta",
"publish:dryrun": "npm run build && npm publish --dry-run"
},
"author": "Christian Nachtigall <cw.nachtigall@gmail.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git://git.harting.dev/vikingowl/snippets-ts.git"
"url": "https://git.harting.dev/vikingowl/snippets-ts"
},
"bugs": {
"url": "https://git.harting.dev/vikingowl/snippets-ts/issues"
@@ -22,14 +29,18 @@
"beta",
"library"
],
"author": "Christian Nachtigall <cw.nachtigall@gmail.com>",
"license": "MIT",
"types": "./dist/index.d.ts",
"packageManager": "yarn@3.2.0",
"exports": {
".": "./lib.index.js"
},
"dependencies": {
"typescript": "^4.6.3"
},
"files": [
"/dist"
]
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.18.0",
"eslint-config-prettier": "^8.5.0",
"prettier": "^2.7.1",
"prettier-eslint": "^15.0.1"
}
}

View File

@@ -1,24 +0,0 @@
export function addGlobalEventListener(
type: string,
selector: string,
callback: (arg0: Event) => void,
options: boolean | AddEventListenerOptions,
parent = document
): void {
parent.addEventListener(
type,
e => {
// @ts-ignore
if (e.target.matches(selector)) callback(e)
},
options
)
}
export function qs(selector: string, parent = document): Element {
return parent.querySelector(selector)
}
export function qsa(selector: string, parent = document): Element[] {
return [...parent.querySelectorAll(selector)]
}

View File

@@ -1,55 +0,0 @@
const CURRENCY_FORMATTER = new Intl.NumberFormat(undefined, {
currency: "EUR",
style: "currency",
})
export function formatCurrency (number: number): string {
return CURRENCY_FORMATTER.format(number)
}
const NUMBER_FORMATTER = new Intl.NumberFormat(undefined)
export function formatNumber (number: number): string {
return NUMBER_FORMATTER.format(number)
}
const COMPACT_NUMBER_FORMATTER = new Intl.NumberFormat(undefined, {
notation: "compact"
})
export function formatCompactNumber (number: number): string {
return COMPACT_NUMBER_FORMATTER.format(number)
}
type DivisionsT = {
amount: number
name:
"year" | "years" |
"quarter" | "quarters" |
"month" | "months" |
"week" | "weeks" |
"day" | "days" |
"hour" | "hours" |
"minute" | "minutes" |
"second" | "seconds"
}
const DIVISTIONS: DivisionsT[] = [
{ amount: 60, name: "seconds" },
{ amount: 60, name: "minutes" },
{ amount: 24, name: "hours" },
{ amount: 7, name: "days" },
{ amount: 4.34524, name: "weeks" },
{ amount: 12, name: "months" },
{ amount: Number.POSITIVE_INFINITY, name: "years" },
]
const RELATIVE_DATE_FORMATTER = new Intl.RelativeTimeFormat(undefined, {
numeric: "auto"
})
export function formatRelativeDate(toDate: Date, fromDate: Date = new Date()) {
let duration = (toDate.getSeconds() - fromDate.getSeconds()) / 1000
for (let i = 0; i <= DIVISTIONS.length; i++) {
const division = DIVISTIONS[i]
if (Math.abs(duration) < division.amount) {
return RELATIVE_DATE_FORMATTER.format(Math.round(duration), division.name)
}
duration /= division.amount
}
}

View File

@@ -1,3 +0,0 @@
export * from "./utils"
export * from "./domUtils"
export * from "./formatters"

View File

@@ -1,3 +0,0 @@
export function sleep (time: number): Promise<unknown> {
return new Promise((resolve => setTimeout(resolve, time)))
}

View File

@@ -1,11 +1,11 @@
{
"compilerOptions": {
"module": "umd",
"target": "es2021",
"module": "CommonJS",
"target": "ESNext",
"declaration": true,
"outDir": "./dist",
"outDir": "./dist"
},
"include": [
"src/**/*"
"lib/**/*"
]
}

View File

@@ -1,34 +0,0 @@
# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!
__metadata:
version: 6
cacheKey: 8
"snippets-ts@workspace:.":
version: 0.0.0-use.local
resolution: "snippets-ts@workspace:."
dependencies:
typescript: ^4.6.3
languageName: unknown
linkType: soft
"typescript@npm:^4.6.3":
version: 4.6.3
resolution: "typescript@npm:4.6.3"
bin:
tsc: bin/tsc
tsserver: bin/tsserver
checksum: 255bb26c8cb846ca689dd1c3a56587af4f69055907aa2c154796ea28ee0dea871535b1c78f85a6212c77f2657843a269c3a742d09d81495b97b914bf7920415b
languageName: node
linkType: hard
"typescript@patch:typescript@^4.6.3#~builtin<compat/typescript>":
version: 4.6.3
resolution: "typescript@patch:typescript@npm%3A4.6.3#~builtin<compat/typescript>::version=4.6.3&hash=bda367"
bin:
tsc: bin/tsc
tsserver: bin/tsserver
checksum: 6bf45caf847062420592e711bc9c28bf5f9a9a7fa8245343b81493e4ededae33f1774009d1234d911422d1646a2c839f44e1a23ecb111b40a60ac2ea4c1482a8
languageName: node
linkType: hard