kontroll 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 NamesMT <https://github.com/namesmt>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # kontroll [![NPM version](https://img.shields.io/npm/v/kontroll?color=a1b858&label=)](https://www.npmjs.com/package/kontroll)
2
+
3
+ **kontroll** ("control") is a small, dead-simple package for function behavior controls like debounce, countdown, throttle (limit).
4
+
5
+ ## Features
6
+ - **100% coverage!**
7
+ - **Self-explained**: for real, every functions and options have TSDoc comments to explain their behavior plus examples at a **hover** *(based on your IDE)*, apart from the already intuitive logic path.
8
+ - **Clearable**: you can stop pending timers by calling the returned clearer function or use the `clear(key)` function.
9
+ - **Promise aware**: avoid duplicated call if your promise haven't settled.
10
+
11
+ ## Usage
12
+ ### Install package:
13
+ ```sh
14
+ # npm
15
+ npm install kontroll
16
+
17
+ # yarn
18
+ yarn add kontroll
19
+
20
+ # pnpm (recommended)
21
+ pnpm install kontroll
22
+ ```
23
+
24
+ ### Import:
25
+ ```js
26
+ // This package exports ESM only.
27
+ import {
28
+ clear,
29
+ countdown, // Can be understand as throttle no leading (execute at end of throttle instead of lead)
30
+ debounce,
31
+ throttle,
32
+ } from 'kontroll'
33
+
34
+ const doSum = (...numbers) => console.log(numbers.reduce((acc, cur) => acc + cur, 0))
35
+ const makeDoSum = (...numbers) => () => doSum(numbers)
36
+
37
+ const clearCountdown = countdown(1000, makeDoSum(1, 2), { key: 'defined', replace: false })
38
+ const clearDebounce = debounce(1000, makeDoSum(3, 4), { key: 34, leading: false })
39
+ const resetThrottle = throttle(1000, makeDoSum(5, 6), { trailing: false })
40
+ ```
41
+
42
+ ## **Notice**
43
+ ### `key` behavior
44
+ Kontroll follows a key-first strategy, as long as things share the same key, they share the same timer.
45
+
46
+ If a `options.key` is not present, key are taken as `callback.toString()`.
47
+
48
+ <!-- Explaining the basic for sleep derived beginner :> -->
49
+ If you call something like:
50
+ ```js
51
+ // * Case 1, (arrow) function with unchanged/variable-only body
52
+ debounce(1000, () => console.log(variable))
53
+
54
+ // * Case 2, declared function
55
+ debounce(1000, makeDoSum(1, 2))
56
+ // For declared function, input could be changed.
57
+ debounce(1000, makeDoSum(2, 3))
58
+ ```
59
+ multiple times,
60
+ The callback are properly debounced, because they have the same callback body.
61
+
62
+ But be noticed, for something like:
63
+ ```js
64
+ debounce(1000, () => console.log('hi'))
65
+ debounce(1000, () => console.log('hello'))
66
+ ```
67
+ The automated key are different for the two calls (because they have different callback body), so they are timed separately.
68
+ In you wish them to have the same timer, you can manually set `options.key` like: `debounce(1000, () => {}, { key: 'KEY' })`
69
+
70
+ ## License
71
+
72
+ [MIT](./LICENSE) License © 2023 [NamesMT](https://github.com/NamesMT)
@@ -0,0 +1,129 @@
1
+ type Fn<T = void> = () => T;
2
+ type FnWithArgs<T = void> = (...args: any) => T;
3
+ interface KontrollStore {
4
+ [x: keyof any]: {
5
+ timer: ReturnType<typeof setTimeout>;
6
+ callback: Fn;
7
+ trailing?: [FnWithArgs, ...any];
8
+ };
9
+ }
10
+ declare function clear(callback: Fn): void;
11
+ declare function clear(key: keyof KontrollStore): void;
12
+ type KontrollClearer = Fn;
13
+ interface KontrollBaseOptions {
14
+ /**
15
+ * Specify a known key if needed
16
+ * @default string // .toString() of the inputted callback
17
+ */
18
+ key?: keyof KontrollStore;
19
+ }
20
+ interface KontrollCountdownOptions extends KontrollBaseOptions {
21
+ /**
22
+ * Replaces the current timed callback
23
+ * @default false
24
+ */
25
+ replace?: boolean;
26
+ }
27
+ /**
28
+ * Countdown for a period of ms then execute the first/replaced callback, based on `options.replace`.
29
+ * Calls while the timer haven't finished are dropped.
30
+ * ---
31
+ *
32
+ * Example
33
+ * ```
34
+ * countdown(1000, doSum(1), { key: 'eg' })
35
+ * // 500ms passed
36
+ * countdown(1000, doSum(2))
37
+ * // 500ms passed
38
+ * // Result: 1
39
+ * ```
40
+ * ---
41
+ *
42
+ * Example with `options.replace=true`:
43
+ * ```
44
+ * countdown(1000, doSum(1))
45
+ * // 500ms passed
46
+ * countdown(1000, doSum(2), { replace: true })
47
+ * // 500ms passed
48
+ * // Result: 2
49
+ * ```
50
+ */
51
+ declare function countdown(ms: number, callback: Fn, options?: KontrollCountdownOptions): KontrollClearer;
52
+ interface KontrollDebounceOptions extends KontrollBaseOptions {
53
+ /**
54
+ * Avoiding initial wait for first call
55
+ * @default false
56
+ */
57
+ leading?: boolean;
58
+ }
59
+ /**
60
+ * Creates a timer that will execute the callback upon finish, calls while the timer haven't finished recreates the timer.
61
+ * If `options.leading`, execute callback immediately for initial call.
62
+ * ---
63
+ *
64
+ * Example:
65
+ * ```
66
+ * debounce(1000, doSum(1))
67
+ * // 500ms passed
68
+ * debounce(1000, doSum(2))
69
+ * // 1000ms passed
70
+ * // Result: 2
71
+ * ```
72
+ * ---
73
+ *
74
+ * Example with `options.leading`:
75
+ * ```
76
+ * debounce(1000, doSum(1), { leading: true })
77
+ * // Result: 1
78
+ * // 500ms passed
79
+ * debounce(1000, doSum(2), { leading: true }) // leading doesn't matter anymore in this timer scope
80
+ * // 500ms passed
81
+ * debounce(1000, doSum(3))
82
+ * // 1000ms passed
83
+ * // Result: 3
84
+ * ```
85
+ */
86
+ declare function debounce(ms: number, callback: Fn, options?: KontrollDebounceOptions): KontrollClearer;
87
+ interface KontrollThrottleOptions extends KontrollBaseOptions {
88
+ /**
89
+ * Perform additional execution with last received arguments
90
+ * @default false
91
+ */
92
+ trailing?: boolean;
93
+ }
94
+ /**
95
+ * Executes the callback, and bypass any subsequent calls for a period of ms.
96
+ * Calls while the timer haven't finished are dropped.
97
+ * If `options.trailing` and calls while the timer haven't finished are received,
98
+ * an additional execution with last received arguments is performed.
99
+ * ---
100
+ *
101
+ * Example:
102
+ * ```
103
+ * throttle(1000, doSum(1))
104
+ * // Result: 1
105
+ * // 500ms passed
106
+ * throttle(1000, doSum(2))
107
+ * // 9999ms passed
108
+ * // (Nothing)
109
+ * ```
110
+ * ---
111
+ *
112
+ * Example with `options.trailing`:
113
+ * ```
114
+ * throttle(1000, doSum(1))
115
+ * // Result: 1
116
+ * // 500ms passed
117
+ * throttle(1000, doSum(2), { trailing: true })
118
+ * // 500ms passed
119
+ * // Result: 2
120
+ * // A timer is also created, so calls after that are still dropped:
121
+ * throttle(1000, doSum(3))
122
+ * // 9999ms passed
123
+ * // (Nothing)
124
+ * ```
125
+ *
126
+ */
127
+ declare function throttle(ms: number, callback: Fn, options?: KontrollThrottleOptions): KontrollClearer;
128
+
129
+ export { type KontrollBaseOptions, type KontrollClearer, type KontrollCountdownOptions, type KontrollDebounceOptions, type KontrollStore, type KontrollThrottleOptions, clear, countdown, debounce, throttle };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ const i={};function o(n){const t=typeof n=="function"?n.toString():n;i[t]&&(clearTimeout(i[t].timer),delete i[t])}async function f(n){if(i[n]){const t=i[n].trailing;await i[n].callback(),o(n),t&&t[0](...t.slice(1))}}function l(n){return()=>{o(n)}}function u(n,t,c){const e=setTimeout(()=>{f(n)},t);return i[n]={timer:e,callback:c},l(n)}function s(n,t,c={}){const{key:e=t.toString(),replace:r=!1}=c;return i[e]?(r&&(i[e].callback=t),l(e)):u(e,n,t)}function g(n,t,c={}){const{key:e=t.toString(),leading:r=!1}=c;if(i[e])o(e);else if(r)return a(n,t,{key:e});return u(e,n,t)}function a(n,t,c={}){const{key:e=t.toString(),trailing:r=!1}=c;return i[e]?(r&&(i[e].trailing=[a,n,t,c]),l(e)):(t(),u(e,n,()=>{}))}export{o as clear,s as countdown,g as debounce,a as throttle};
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "kontroll",
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "packageManager": "pnpm@8.12.0",
6
+ "description": "",
7
+ "author": "NamesMT <dangquoctrung123@gmail.com>",
8
+ "license": "MIT",
9
+ "funding": "https://github.com/sponsors/namesmt",
10
+ "homepage": "https://github.com/namesmt/kontroll#readme",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/namesmt/kontroll.git"
14
+ },
15
+ "bugs": "https://github.com/namesmt/kontroll/issues",
16
+ "keywords": [],
17
+ "sideEffects": false,
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.mts",
21
+ "import": "./dist/index.mjs"
22
+ }
23
+ },
24
+ "source": "./src/index.ts",
25
+ "main": "./dist/index.mjs",
26
+ "module": "./dist/index.mjs",
27
+ "types": "./dist/index.d.mts",
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "engines": {
32
+ "node": ">=18.0.0"
33
+ },
34
+ "scripts": {
35
+ "start": "NODE_ENV=dev tsx src/index.ts",
36
+ "watch": "NODE_ENV=dev tsx watch src/index.ts",
37
+ "stub": "unbuild --stub",
38
+ "dev": "pnpm run watch",
39
+ "play": "pnpm run stub && pnpm run --filter playground dev",
40
+ "play:useBuild": "pnpm run build && pnpm run --filter playground dev",
41
+ "lint": "eslint .",
42
+ "test": "vitest",
43
+ "test:types": "tsc --noEmit --skipLibCheck",
44
+ "check": "pnpm lint && pnpm test:types && vitest run --coverage",
45
+ "build": "unbuild",
46
+ "release": "pnpm dlx changelogen@latest --release --push --publish",
47
+ "prepare": "simple-git-hooks",
48
+ "prepublishOnly": "pnpm run build"
49
+ },
50
+ "dependencies": {
51
+ "consola": "^3.2.3",
52
+ "std-env": "^3.6.0"
53
+ },
54
+ "devDependencies": {
55
+ "@antfu/eslint-config": "^2.4.4",
56
+ "@types/node": "^20.10.4",
57
+ "@unocss/eslint-plugin": "^0.58.0",
58
+ "@vitest/coverage-v8": "^1.0.4",
59
+ "eslint": "^8.55.0",
60
+ "lint-staged": "^15.2.0",
61
+ "simple-git-hooks": "^2.9.0",
62
+ "tsx": "^4.6.2",
63
+ "typescript": "^5.3.3",
64
+ "unbuild": "^2.0.0",
65
+ "vitest": "^1.0.4"
66
+ },
67
+ "pnpm": {
68
+ "overrides": {
69
+ "hasown": "npm:@nolyfill/hasown@latest"
70
+ }
71
+ },
72
+ "simple-git-hooks": {
73
+ "pre-commit": "pnpm lint-staged"
74
+ },
75
+ "lint-staged": {
76
+ "*": "eslint --fix"
77
+ }
78
+ }