danholibraryjs 1.5.0 → 1.8.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.
Files changed (112) hide show
  1. package/.gitattributes +2 -2
  2. package/README.md +12 -304
  3. package/Time.xlsx +0 -0
  4. package/dist/Classes/{Event.d.ts → Events/Event.d.ts} +9 -8
  5. package/dist/Classes/{Event.js → Events/Event.js} +17 -9
  6. package/dist/Classes/{EventCollection.d.ts → Events/EventCollection.d.ts} +10 -10
  7. package/dist/Classes/{EventCollection.js → Events/EventCollection.js} +28 -29
  8. package/dist/Classes/{EventEmitter.d.ts → Events/EventEmitter.d.ts} +33 -7
  9. package/dist/Classes/{EventEmitter.js → Events/EventEmitter.js} +33 -3
  10. package/dist/Classes/Events/index.d.ts +3 -0
  11. package/dist/Classes/Events/index.js +19 -0
  12. package/dist/Classes/Time/Date.d.ts +147 -0
  13. package/dist/Classes/Time/Date.js +238 -0
  14. package/dist/Classes/Time/Time.d.ts +65 -0
  15. package/dist/Classes/Time/Time.js +117 -0
  16. package/dist/Classes/Time/TimeProperties.d.ts +3 -0
  17. package/dist/{Interfaces/BaseEventInterface.js → Classes/Time/TimeProperties.js} +0 -0
  18. package/dist/Classes/Time/TimeSpan.d.ts +123 -0
  19. package/dist/Classes/Time/TimeSpan.js +179 -0
  20. package/dist/Classes/Time/index.d.ts +4 -0
  21. package/dist/Classes/Time/index.js +20 -0
  22. package/dist/Classes/index.d.ts +2 -3
  23. package/dist/Classes/index.js +7 -4
  24. package/dist/Classes/store.d.ts +79 -0
  25. package/dist/Classes/store.js +85 -0
  26. package/dist/Extensions/Array.d.ts +31 -0
  27. package/dist/Extensions/Array.js +26 -0
  28. package/dist/Extensions/Map.d.ts +38 -0
  29. package/dist/Extensions/Map.js +31 -0
  30. package/dist/Extensions/Object.d.ts +16 -0
  31. package/dist/Extensions/Object.js +8 -0
  32. package/dist/Extensions/String.d.ts +26 -0
  33. package/dist/Extensions/String.js +17 -0
  34. package/dist/Extensions/index.d.ts +29 -0
  35. package/dist/Extensions/index.js +71 -0
  36. package/dist/Functions/GetCSSProperty.d.ts +15 -0
  37. package/dist/Functions/GetCSSProperty.js +26 -0
  38. package/dist/Functions/HTMLEvent.d.ts +6 -0
  39. package/dist/Functions/HTMLEvent.js +6 -0
  40. package/dist/Functions/SetNavigationSelected.js +2 -0
  41. package/dist/Functions/index.d.ts +1 -0
  42. package/dist/Functions/index.js +6 -1
  43. package/dist/Interfaces/ElementOptions.d.ts +12 -15
  44. package/dist/Interfaces/IReplacement.d.ts +1 -1
  45. package/dist/Interfaces/index.d.ts +0 -1
  46. package/dist/Interfaces/index.js +5 -2
  47. package/dist/Types/BetterTypes.d.ts +9 -0
  48. package/dist/{Interfaces/IHTMLEvent.js → Types/BetterTypes.js} +0 -0
  49. package/dist/Types/Date.d.ts +6 -0
  50. package/dist/Types/{EventHandler.js → Date.js} +0 -0
  51. package/dist/Types/Events.d.ts +10 -0
  52. package/dist/Types/{IElement.js → Events.js} +0 -0
  53. package/dist/Types/PropertiesWith.d.ts +13 -0
  54. package/dist/Types/{StringRegex.js → PropertiesWith.js} +0 -0
  55. package/dist/Types/TransformTypes.d.ts +13 -0
  56. package/dist/Types/TransformTypes.js +2 -0
  57. package/dist/Types/index.d.ts +31 -3
  58. package/dist/Types/index.js +10 -4
  59. package/dist/index.d.ts +5 -5
  60. package/dist/index.js +19 -10
  61. package/docs/Classes.md +488 -0
  62. package/docs/Extensions.md +146 -0
  63. package/docs/Functions.md +53 -0
  64. package/docs/Interfaces.md +34 -0
  65. package/docs/Types.md +137 -0
  66. package/docs/index.md +29 -0
  67. package/package.json +22 -21
  68. package/src/Classes/{Event.ts → Events/Event.ts} +19 -14
  69. package/src/Classes/Events/EventCollection.ts +109 -0
  70. package/src/Classes/{EventEmitter.ts → Events/EventEmitter.ts} +37 -11
  71. package/src/Classes/Events/index.ts +3 -0
  72. package/src/Classes/Time/Date.ts +264 -0
  73. package/src/Classes/Time/Time.ts +134 -0
  74. package/src/Classes/Time/TimeProperties.ts +3 -0
  75. package/src/Classes/Time/TimeSpan.ts +195 -0
  76. package/src/Classes/Time/index.ts +4 -0
  77. package/src/Classes/index.ts +2 -3
  78. package/src/Classes/store.ts +95 -0
  79. package/src/Extensions/Array.ts +57 -0
  80. package/src/Extensions/Map.ts +73 -0
  81. package/src/Extensions/Object.ts +25 -0
  82. package/src/Extensions/String.ts +43 -0
  83. package/src/Extensions/index.ts +83 -0
  84. package/src/Functions/GetCSSProperty.ts +27 -0
  85. package/src/Functions/HTMLEvent.ts +6 -0
  86. package/src/Functions/SetNavigationSelected.ts +1 -0
  87. package/src/Functions/index.ts +2 -1
  88. package/src/Interfaces/ElementOptions.ts +18 -14
  89. package/src/Interfaces/IReplacement.ts +1 -1
  90. package/src/Interfaces/index.ts +1 -2
  91. package/src/Types/BetterTypes.ts +10 -0
  92. package/src/Types/Date.ts +7 -0
  93. package/src/Types/Events.ts +15 -0
  94. package/src/Types/PropertiesWith.ts +14 -0
  95. package/src/Types/TransformTypes.ts +18 -0
  96. package/src/Types/index.ts +36 -3
  97. package/src/index.ts +5 -6
  98. package/tsconfig.json +99 -7
  99. package/dist/Extensions.d.ts +0 -85
  100. package/dist/Extensions.js +0 -84
  101. package/dist/Interfaces/BaseEventInterface.d.ts +0 -4
  102. package/dist/Interfaces/IHTMLEvent.d.ts +0 -4
  103. package/dist/Types/EventHandler.d.ts +0 -7
  104. package/dist/Types/IElement.d.ts +0 -9
  105. package/dist/Types/StringRegex.d.ts +0 -2
  106. package/src/Classes/EventCollection.ts +0 -116
  107. package/src/Extensions.ts +0 -185
  108. package/src/Interfaces/BaseEventInterface.ts +0 -4
  109. package/src/Types/EventHandler.ts +0 -12
  110. package/src/Types/IElement.ts +0 -9
  111. package/src/Types/StringRegex.ts +0 -2
  112. package/test.js +0 -20
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Time = exports.ms = exports.ValidTime = void 0;
4
+ exports.ValidTime = /^(\d+(?:\.|,)?\d*)(ms|s|m|h|d|w|M|y)$/;
5
+ /**
6
+ * Converts input into milliseconds
7
+ * @param input Input to convert to ms. 1s | 2m | 3h | 1M | 60000
8
+ * @returns Millisecond value of input
9
+ */
10
+ function ms(input) {
11
+ if (typeof input === 'number')
12
+ return input;
13
+ const match = input.match(exports.ValidTime);
14
+ if (!match)
15
+ throw Error(`Invalid input string "${input}"`);
16
+ match.shift();
17
+ const [value, unit] = match;
18
+ // console.log({ value, unit, input, match });
19
+ const units = new Map([
20
+ ['ms', Time.millisecond],
21
+ ['s', Time.second],
22
+ ['m', Time.minute],
23
+ ['h', Time.hour],
24
+ ['d', Time.day],
25
+ ['w', Time.week],
26
+ ['M', Time.month],
27
+ ['y', Time.year]
28
+ ]);
29
+ return parseInt(value) * units.get(unit);
30
+ }
31
+ exports.ms = ms;
32
+ /**
33
+ * Time utility class
34
+ * @borrows TimeDelay
35
+ * @borrows ms
36
+ */
37
+ class Time {
38
+ /**
39
+ * Array of amount of days in the months. 0 indexed
40
+ */
41
+ static get daysInMonth() {
42
+ return [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
43
+ }
44
+ /**
45
+ * Amount of weeks per year
46
+ */
47
+ static get weeksInYear() {
48
+ return Time.daysInYear * Time.day / Time.week;
49
+ }
50
+ /**
51
+ * Amount of days per year
52
+ */
53
+ static get daysInYear() {
54
+ return Time.year / Time.day;
55
+ ;
56
+ }
57
+ /**
58
+ * Returns function that converts value into double digit string
59
+ * @returns (value: number): string
60
+ */
61
+ static DoubleDigit(value) {
62
+ return value.toString().length < 2 ? `0${value}` : value.toString();
63
+ }
64
+ static th(value, includeValue = false) {
65
+ const th = (() => {
66
+ switch (value) {
67
+ case 1: return 'st';
68
+ case 2: return 'nd';
69
+ case 3: return 'rd';
70
+ default: return 'th';
71
+ }
72
+ })();
73
+ return includeValue ? value + th : th;
74
+ }
75
+ /**
76
+ * Array of names of the months. 0 idnexed
77
+ */
78
+ static get MonthNames() {
79
+ return new Array('Janurary', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
80
+ }
81
+ /**
82
+ * Array of names of the days of the week. 0 indexed
83
+ */
84
+ static get DayNames() {
85
+ return new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
86
+ }
87
+ /** Millisecond in milliseconds (I know that sounds weird but the others make sense) */
88
+ static get millisecond() { return 1; }
89
+ /** Second in milliseconds */
90
+ static get second() { return Time.millisecond * 1000; }
91
+ /** Minute in milliseconds */
92
+ static get minute() { return Time.second * 60; }
93
+ /** Hour in milliseconds */
94
+ static get hour() { return Time.minute * 60; }
95
+ /** Day in milliseconds */
96
+ static get day() { return Time.hour * 24; }
97
+ /** Week in milliseconds */
98
+ static get week() { return Time.day * 7; }
99
+ /** Month in milliseconds */
100
+ static get month() {
101
+ return Time.avgMonth * Time.day;
102
+ }
103
+ /** Year in milliseconds */
104
+ static get year() {
105
+ const now = new Date();
106
+ return (365 + (now.getFullYear() % 4 == 0 ? 1 : 0)) * Time.day;
107
+ }
108
+ /** Average month in milliseconds */
109
+ static get avgMonth() {
110
+ return Math.round(this.daysInMonth.reduce((result, num) => result += num, 0) / 12);
111
+ }
112
+ static ms(input) {
113
+ return ms(input);
114
+ }
115
+ }
116
+ exports.Time = Time;
117
+ exports.default = Time;
@@ -0,0 +1,3 @@
1
+ declare type TimeKeys = 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond';
2
+ export declare type TimeProperties<Plural extends boolean = false> = Record<Plural extends true ? `${TimeKeys}s` : TimeKeys, number>;
3
+ export default TimeProperties;
@@ -0,0 +1,123 @@
1
+ import { TransformType } from "../../Types";
2
+ import DanhoDate, { DanhoDateConstructor } from "./Date";
3
+ import TimeProperties from "./TimeProperties";
4
+ /**
5
+ * What properties to include when using TimeSpan.toString(format: TimeSpanFormat): string
6
+ */
7
+ export declare type TimeSpanFormat = Partial<TransformType<TimeProperties<true>, number, boolean>>;
8
+ /**
9
+ * Timespan between 2 dates.
10
+ * @borrows TimeSpanValue
11
+ * @borrows Time
12
+ * @borrows TimeProperties
13
+ */
14
+ export declare class TimeSpan implements TimeProperties<true> {
15
+ constructor(from: DanhoDateConstructor, to?: DanhoDateConstructor);
16
+ /**
17
+ * Which of the dates in constructor had the highest getTime()
18
+ */
19
+ private _highest;
20
+ /**
21
+ * Which of the dates in constructor had the lowest getTime()
22
+ */
23
+ private _lowest;
24
+ /**
25
+ * The time difference between highest and lowest
26
+ * @returns Time difference in ms between this._highest and this._lowest
27
+ */
28
+ private _getTimeDifference;
29
+ /**
30
+ * Reduces ms into provided timeDifference
31
+ * @param ms Millisecond value to reduce
32
+ * @param timeDifference Time difference in ms that for each timeDifference in ms, add 1 to result
33
+ * @returns How many times timeDifference fits in ms
34
+ */
35
+ private _reduceTime;
36
+ /**
37
+ * Total years between dates
38
+ */
39
+ years: number;
40
+ /**
41
+ * Total months between dates
42
+ */
43
+ months: number;
44
+ /**
45
+ * Total weeks between dates
46
+ */
47
+ weeks: number;
48
+ /**
49
+ * Total days between dates
50
+ */
51
+ days: number;
52
+ /**
53
+ * Total hours between dates
54
+ */
55
+ hours: number;
56
+ /**
57
+ * Total minutes between dates
58
+ */
59
+ minutes: number;
60
+ /**
61
+ * Total seconds between dates
62
+ */
63
+ seconds: number;
64
+ /**
65
+ * Total milliseconds between dates
66
+ */
67
+ milliseconds: number;
68
+ /**
69
+ * Get the total unit time between the two dates
70
+ * @param unit Time unit in milliseconds
71
+ * @returns How many times that unit fits in total ms between the two dates
72
+ */
73
+ private _getTotalUnit;
74
+ /**
75
+ * Get the maximum amount of months between the two dates
76
+ * @returns Number of max amount of months that are between the two dates
77
+ */
78
+ getTotalMonths(): number;
79
+ /**
80
+ * Get the maximum amount of weeks between the two dates
81
+ * @returns Number of max amount of weeks that are between the two dates
82
+ */
83
+ getTotalWeeks(): number;
84
+ /**
85
+ * Get the maximum amount of days between the two dates
86
+ * @returns Number of max amount of days that are between the two dates
87
+ */
88
+ getTotalDays(): number;
89
+ /**
90
+ * Get the maximum amount of hours between the two dates
91
+ * @returns Number of max amount of hours that are between the two dates
92
+ */
93
+ getTotalHours(): number;
94
+ /**
95
+ * Get the maximum amount of minutes between the two dates
96
+ * @returns Number of max amount of minutes that are between the two dates
97
+ */
98
+ getTotalMinutes(): number;
99
+ /**
100
+ * Get the maximum amount of seconds between the two dates
101
+ * @returns Number of max amount of seconds that are between the two dates
102
+ */
103
+ getTotalSeconds(): number;
104
+ /**
105
+ * Get the maximum amount of milliseconds between the two dates
106
+ * @returns Number of max amount of milliseconds that are between the two dates
107
+ */
108
+ getTotalMilliseconds(): number;
109
+ /**
110
+ * Start date of timespan
111
+ */
112
+ from: DanhoDate;
113
+ /**
114
+ * End date of timespan
115
+ */
116
+ to: DanhoDate;
117
+ /**
118
+ * Timespan is in the past
119
+ */
120
+ pastTense: boolean;
121
+ toString(format?: TimeSpanFormat): string;
122
+ }
123
+ export default TimeSpan;
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TimeSpan = void 0;
7
+ const Date_1 = __importDefault(require("./Date"));
8
+ const Time_1 = __importDefault(require("./Time"));
9
+ /**
10
+ * Timespan between 2 dates.
11
+ * @borrows TimeSpanValue
12
+ * @borrows Time
13
+ * @borrows TimeProperties
14
+ */
15
+ class TimeSpan {
16
+ constructor(from, to = Date.now()) {
17
+ //General properties
18
+ this.from = new Date_1.default(from);
19
+ this.to = new Date_1.default(to);
20
+ //Ensure from < to
21
+ this._highest = this.from.time > this.to.time ? this.from : this.to;
22
+ this._lowest = this.from == this._highest ? this.to : this.from;
23
+ this.pastTense = this._highest !== this.to;
24
+ this._highest = new Date_1.default(this._highest.time + Time_1.default.millisecond);
25
+ let timeDifference = this._getTimeDifference();
26
+ //Calculate time difference between from & to and set to object properties
27
+ [this.years, timeDifference] = this._reduceTime(Time_1.default.year, timeDifference);
28
+ [this.months, timeDifference] = this._reduceTime(Time_1.default.month, timeDifference);
29
+ [this.weeks, timeDifference] = this._reduceTime(Time_1.default.week, timeDifference);
30
+ [this.days, timeDifference] = this._reduceTime(Time_1.default.day, timeDifference);
31
+ [this.hours, timeDifference] = this._reduceTime(Time_1.default.hour, timeDifference);
32
+ [this.minutes, timeDifference] = this._reduceTime(Time_1.default.minute, timeDifference);
33
+ [this.seconds, timeDifference] = this._reduceTime(Time_1.default.second, timeDifference);
34
+ [this.milliseconds, timeDifference] = this._reduceTime(Time_1.default.millisecond, timeDifference);
35
+ }
36
+ /**
37
+ * Which of the dates in constructor had the highest getTime()
38
+ */
39
+ _highest;
40
+ /**
41
+ * Which of the dates in constructor had the lowest getTime()
42
+ */
43
+ _lowest;
44
+ /**
45
+ * The time difference between highest and lowest
46
+ * @returns Time difference in ms between this._highest and this._lowest
47
+ */
48
+ _getTimeDifference() {
49
+ return Math.round(this._highest.time - this._lowest.time);
50
+ }
51
+ /**
52
+ * Reduces ms into provided timeDifference
53
+ * @param ms Millisecond value to reduce
54
+ * @param timeDifference Time difference in ms that for each timeDifference in ms, add 1 to result
55
+ * @returns How many times timeDifference fits in ms
56
+ */
57
+ _reduceTime(ms, timeDifference) {
58
+ let result = 0;
59
+ while (timeDifference > ms) {
60
+ timeDifference -= ms;
61
+ result++;
62
+ }
63
+ return [result, timeDifference];
64
+ }
65
+ /**
66
+ * Total years between dates
67
+ */
68
+ years;
69
+ /**
70
+ * Total months between dates
71
+ */
72
+ months;
73
+ /**
74
+ * Total weeks between dates
75
+ */
76
+ weeks;
77
+ /**
78
+ * Total days between dates
79
+ */
80
+ days;
81
+ /**
82
+ * Total hours between dates
83
+ */
84
+ hours;
85
+ /**
86
+ * Total minutes between dates
87
+ */
88
+ minutes;
89
+ /**
90
+ * Total seconds between dates
91
+ */
92
+ seconds;
93
+ /**
94
+ * Total milliseconds between dates
95
+ */
96
+ milliseconds;
97
+ /**
98
+ * Get the total unit time between the two dates
99
+ * @param unit Time unit in milliseconds
100
+ * @returns How many times that unit fits in total ms between the two dates
101
+ */
102
+ _getTotalUnit(unit) {
103
+ return this._reduceTime(unit, this._getTimeDifference())[0];
104
+ }
105
+ /**
106
+ * Get the maximum amount of months between the two dates
107
+ * @returns Number of max amount of months that are between the two dates
108
+ */
109
+ getTotalMonths() {
110
+ return this._getTotalUnit(Time_1.default.month);
111
+ }
112
+ /**
113
+ * Get the maximum amount of weeks between the two dates
114
+ * @returns Number of max amount of weeks that are between the two dates
115
+ */
116
+ getTotalWeeks() {
117
+ return this._getTotalUnit(Time_1.default.week);
118
+ }
119
+ /**
120
+ * Get the maximum amount of days between the two dates
121
+ * @returns Number of max amount of days that are between the two dates
122
+ */
123
+ getTotalDays() {
124
+ return this._getTotalUnit(Time_1.default.day);
125
+ }
126
+ /**
127
+ * Get the maximum amount of hours between the two dates
128
+ * @returns Number of max amount of hours that are between the two dates
129
+ */
130
+ getTotalHours() {
131
+ return this._getTotalUnit(Time_1.default.hour);
132
+ }
133
+ /**
134
+ * Get the maximum amount of minutes between the two dates
135
+ * @returns Number of max amount of minutes that are between the two dates
136
+ */
137
+ getTotalMinutes() {
138
+ return this._getTotalUnit(Time_1.default.minute);
139
+ }
140
+ /**
141
+ * Get the maximum amount of seconds between the two dates
142
+ * @returns Number of max amount of seconds that are between the two dates
143
+ */
144
+ getTotalSeconds() {
145
+ return this._getTotalUnit(Time_1.default.second);
146
+ }
147
+ /**
148
+ * Get the maximum amount of milliseconds between the two dates
149
+ * @returns Number of max amount of milliseconds that are between the two dates
150
+ */
151
+ getTotalMilliseconds() {
152
+ return this._getTotalUnit(Time_1.default.millisecond);
153
+ }
154
+ /**
155
+ * Start date of timespan
156
+ */
157
+ from;
158
+ /**
159
+ * End date of timespan
160
+ */
161
+ to;
162
+ /**
163
+ * Timespan is in the past
164
+ */
165
+ pastTense;
166
+ toString(format) {
167
+ //console.log(`${this.years}Y ${this.months}M ${this.weeks}w ${this.days}d ${this.hours}h ${this.minutes}m ${this.seconds}s ${this.milliseconds}ms`);
168
+ const times = [this.years, this.months, this.weeks, this.days, this.hours, this.minutes, this.seconds, this.milliseconds];
169
+ const timeMsg = ["year", "month", "week", "day", "hour", "minute", "second", "millisecond"];
170
+ const result = times.reduce((result, time, i) => (
171
+ // If time is above 0, format is provided, a property matches current property and said property is true, append addition else return result
172
+ time > 0 && (format ? timeMsg[i] in format && format[timeMsg[i]] === true : true) ?
173
+ `${result}${times[i]} ${timeMsg[i]}${times[i] != 1 ? 's' : ''}, ` :
174
+ result), '');
175
+ return result.length > 2 && result.substring(0, result.length - 2) || '';
176
+ }
177
+ }
178
+ exports.TimeSpan = TimeSpan;
179
+ exports.default = TimeSpan;
@@ -0,0 +1,4 @@
1
+ export * from './Date';
2
+ export * from './Time';
3
+ export * from './TimeProperties';
4
+ export * from './TimeSpan';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./Date"), exports);
18
+ __exportStar(require("./Time"), exports);
19
+ __exportStar(require("./TimeProperties"), exports);
20
+ __exportStar(require("./TimeSpan"), exports);
@@ -1,3 +1,2 @@
1
- export * from './EventEmitter';
2
- export * from './EventCollection';
3
- export * from './Event';
1
+ export * from './Events';
2
+ export * from './Time';
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -10,6 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
15
  };
12
16
  Object.defineProperty(exports, "__esModule", { value: true });
13
- __exportStar(require("./EventEmitter"), exports);
14
- __exportStar(require("./EventCollection"), exports);
15
- __exportStar(require("./Event"), exports);
17
+ __exportStar(require("./Events"), exports);
18
+ __exportStar(require("./Time"), exports);
@@ -0,0 +1,79 @@
1
+ import { Arrayable } from "../Types";
2
+ import { EventEmitter } from "./Events";
3
+ export declare type Reducer<State, Types extends Record<string, any[]>, Action extends keyof Types> = (state: State, ...args: Types[Action]) => State;
4
+ /**
5
+ * EventEmitter, but it stores state and handles state change with reducers
6
+ *
7
+ * @Initialization Actions & initial state must be defined in type parameters. InitialState must be provided in constructor, whereas reducer is optional.
8
+ * The ActionType must have properties as strings and values as arrays.
9
+ *
10
+ * @HandlingActions Reducers can be added through constructor or using Store.on('action', reducer) or Store.once('action', reducer).
11
+ * Every state change must return the next state, apart from 'stateChange', which returns void/any
12
+ * Emit/Dispatch an action using Store.dispatch('action', ...args), ...args being the parameters from the ActionType.
13
+ * Store.emit should NOT be used, as it doesn't update the Store's state.
14
+ *
15
+ * Reducer functions can be removed using Store.off('action', reducer);
16
+ *
17
+ * @borrows EventEmitter
18
+ * @borrows Arrayable
19
+ *
20
+ * @example ```ts
21
+ * import { Store } from 'danholibraryjs';
22
+ *
23
+ * type Todo = {
24
+ * id: string,
25
+ * text: string,
26
+ * completed: boolean
27
+ * }
28
+ *
29
+ * type TodoActions = {
30
+ * create: [text: string],
31
+ * update: [id: string, text: string],
32
+ * toggleComplete: [id: string, force?: boolean],
33
+ * delete: [id: string],
34
+ * }
35
+ *
36
+ * const store = new Store<Array<Todo>, TodoActions>(new Array<Todo>(), new Map([
37
+ * create: (state, text) => {
38
+ * return [...state, {
39
+ * id: Math.random().toString(),
40
+ * text,
41
+ * completed: false
42
+ * }];
43
+ * },
44
+ * toggleComplete: (state, id, force) => {
45
+ * const todo = state.find(todo => todo.id === id);
46
+ * if (!todo) return state;
47
+ *
48
+ * return state.map(todo => (
49
+ * todo.id === id ? {
50
+ * ...todo,
51
+ * completed: force === undefined ? !todo.completed : force
52
+ * } : todo
53
+ * ));
54
+ * }
55
+ * ]));
56
+ *
57
+ * store.on('delete', (state, id) => {
58
+ * return state.filter(todo => todo.id !== id);
59
+ * });
60
+ *
61
+ * store.on('stateChange', (prevState, currentState) => console.log('State change', prevState, currentState));
62
+ *
63
+ * store.dispatch('create', 'Make store!');
64
+ *
65
+ * ```
66
+ */
67
+ export declare class Store<State extends object, ActionTypes extends Record<string, any[]>, Actions extends {
68
+ [Action in keyof ActionTypes]: Array<Reducer<State, ActionTypes, Action>>;
69
+ } = {
70
+ [Action in keyof ActionTypes]: Array<Reducer<State, ActionTypes, Action>>;
71
+ }> extends EventEmitter<Record<keyof Actions, ActionTypes[keyof ActionTypes]> & Record<'stateChange', [previous: State, current: State]>> {
72
+ constructor(state: State, actions?: {
73
+ [Action in keyof ActionTypes]?: Arrayable<Reducer<State, ActionTypes, Action>>;
74
+ });
75
+ private _state;
76
+ get state(): State;
77
+ dispatch<Action extends keyof ActionTypes>(action: Action, ...args: ActionTypes[Action]): State;
78
+ }
79
+ export default Store;
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Store = void 0;
4
+ const Events_1 = require("./Events");
5
+ /**
6
+ * EventEmitter, but it stores state and handles state change with reducers
7
+ *
8
+ * @Initialization Actions & initial state must be defined in type parameters. InitialState must be provided in constructor, whereas reducer is optional.
9
+ * The ActionType must have properties as strings and values as arrays.
10
+ *
11
+ * @HandlingActions Reducers can be added through constructor or using Store.on('action', reducer) or Store.once('action', reducer).
12
+ * Every state change must return the next state, apart from 'stateChange', which returns void/any
13
+ * Emit/Dispatch an action using Store.dispatch('action', ...args), ...args being the parameters from the ActionType.
14
+ * Store.emit should NOT be used, as it doesn't update the Store's state.
15
+ *
16
+ * Reducer functions can be removed using Store.off('action', reducer);
17
+ *
18
+ * @borrows EventEmitter
19
+ * @borrows Arrayable
20
+ *
21
+ * @example ```ts
22
+ * import { Store } from 'danholibraryjs';
23
+ *
24
+ * type Todo = {
25
+ * id: string,
26
+ * text: string,
27
+ * completed: boolean
28
+ * }
29
+ *
30
+ * type TodoActions = {
31
+ * create: [text: string],
32
+ * update: [id: string, text: string],
33
+ * toggleComplete: [id: string, force?: boolean],
34
+ * delete: [id: string],
35
+ * }
36
+ *
37
+ * const store = new Store<Array<Todo>, TodoActions>(new Array<Todo>(), new Map([
38
+ * create: (state, text) => {
39
+ * return [...state, {
40
+ * id: Math.random().toString(),
41
+ * text,
42
+ * completed: false
43
+ * }];
44
+ * },
45
+ * toggleComplete: (state, id, force) => {
46
+ * const todo = state.find(todo => todo.id === id);
47
+ * if (!todo) return state;
48
+ *
49
+ * return state.map(todo => (
50
+ * todo.id === id ? {
51
+ * ...todo,
52
+ * completed: force === undefined ? !todo.completed : force
53
+ * } : todo
54
+ * ));
55
+ * }
56
+ * ]));
57
+ *
58
+ * store.on('delete', (state, id) => {
59
+ * return state.filter(todo => todo.id !== id);
60
+ * });
61
+ *
62
+ * store.on('stateChange', (prevState, currentState) => console.log('State change', prevState, currentState));
63
+ *
64
+ * store.dispatch('create', 'Make store!');
65
+ *
66
+ * ```
67
+ */
68
+ class Store extends Events_1.EventEmitter {
69
+ constructor(state, actions = {}) {
70
+ super(new Map(...Object.entries(actions).map(([action, reducers]) => [action, reducers])));
71
+ this._state = state;
72
+ }
73
+ _state;
74
+ get state() {
75
+ return this._state;
76
+ }
77
+ dispatch(action, ...args) {
78
+ const previous = { ...this._state };
79
+ this._state = super.emit(action, ...args).reduce((state, returned) => ({ ...state, ...returned }), this.state);
80
+ super.emit('stateChange', ...[previous, this.state]);
81
+ return this.state;
82
+ }
83
+ }
84
+ exports.Store = Store;
85
+ exports.default = Store;
@@ -0,0 +1,31 @@
1
+ export {};
2
+ declare type UpdateFinder<T> = (item: T, index: number, self: Array<T>) => boolean;
3
+ declare global {
4
+ interface Array<T> {
5
+ /**
6
+ * Pushes items to array and returns self with new items
7
+ * @param items Items to add to array
8
+ */
9
+ add(...items: Array<T>): this;
10
+ /**
11
+ * Update an item in array
12
+ * @param old The old value or index to update
13
+ * @param updated Updated value
14
+ */
15
+ update(old: T | number | UpdateFinder<T>, updated: T): T;
16
+ /**
17
+ * Removes item from array and returns self without item
18
+ * @param item Item or index to remove
19
+ */
20
+ remove(item: T | number): this;
21
+ /**
22
+ * Returns a random element from array
23
+ */
24
+ random(): T;
25
+ /**
26
+ * Returns item matching index. If negative number, subtracts number from length
27
+ * @param i Index of item
28
+ */
29
+ index(i: number): T;
30
+ }
31
+ }