@naturalcycles/js-lib 14.96.1 → 14.98.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.
@@ -48,7 +48,7 @@ class LocalTime {
48
48
  date = new Date(d * 1000);
49
49
  }
50
50
  else {
51
- date = new Date(d);
51
+ date = new Date(d.slice(0, 19));
52
52
  }
53
53
  // validation
54
54
  if (isNaN(date.getDate())) {
@@ -60,6 +60,28 @@ class LocalTime {
60
60
  // }
61
61
  return new LocalTime(date, false);
62
62
  }
63
+ static parseToDate(d) {
64
+ if (d instanceof LocalTime)
65
+ return d.$date;
66
+ if (d instanceof Date)
67
+ return d;
68
+ const date = typeof d === 'number' ? new Date(d * 1000) : new Date(d);
69
+ if (isNaN(date.getDate())) {
70
+ throw new TypeError(`Cannot parse "${d}" to Date`);
71
+ }
72
+ return date;
73
+ }
74
+ static parseToUnixTimestamp(d) {
75
+ if (typeof d === 'number')
76
+ return d;
77
+ if (d instanceof LocalTime)
78
+ return d.unix();
79
+ const date = d instanceof Date ? d : new Date(d);
80
+ if (isNaN(date.getDate())) {
81
+ throw new TypeError(`Cannot parse "${d}" to UnixTimestamp`);
82
+ }
83
+ return date.valueOf() / 1000;
84
+ }
63
85
  static isValid(d) {
64
86
  return this.parseOrNull(d) !== null;
65
87
  }
@@ -118,7 +140,7 @@ class LocalTime {
118
140
  month(v) {
119
141
  return v === undefined ? this.get('month') : this.set('month', v);
120
142
  }
121
- date(v) {
143
+ day(v) {
122
144
  return v === undefined ? this.get('day') : this.set('day', v);
123
145
  }
124
146
  hour(v) {
@@ -164,7 +186,7 @@ class LocalTime {
164
186
  return Math.abs(this.diff(other, unit));
165
187
  }
166
188
  diff(other, unit) {
167
- const date2 = LocalTime.of(other).$date;
189
+ const date2 = LocalTime.parseToDate(other);
168
190
  if (unit === 'year') {
169
191
  return this.$date.getFullYear() - date2.getFullYear();
170
192
  }
@@ -241,14 +263,16 @@ class LocalTime {
241
263
  isSame(d) {
242
264
  return this.cmp(d) === 0;
243
265
  }
244
- isBefore(d) {
245
- return this.cmp(d) === -1;
266
+ isBefore(d, inclusive = false) {
267
+ const r = this.cmp(d);
268
+ return r === -1 || (r === 0 && inclusive);
246
269
  }
247
270
  isSameOrBefore(d) {
248
271
  return this.cmp(d) <= 0;
249
272
  }
250
- isAfter(d) {
251
- return this.cmp(d) === 1;
273
+ isAfter(d, inclusive = false) {
274
+ const r = this.cmp(d);
275
+ return r === 1 || (r === 0 && inclusive);
252
276
  }
253
277
  isSameOrAfter(d) {
254
278
  return this.cmp(d) >= 0;
@@ -269,7 +293,7 @@ class LocalTime {
269
293
  */
270
294
  cmp(d) {
271
295
  const t1 = this.$date.valueOf();
272
- const t2 = LocalTime.of(d).$date.valueOf();
296
+ const t2 = LocalTime.parseToDate(d).valueOf();
273
297
  if (t1 === t2)
274
298
  return 0;
275
299
  return t1 < t2 ? -1 : 1;
@@ -295,8 +319,8 @@ class LocalTime {
295
319
  second: this.$date.getSeconds(),
296
320
  };
297
321
  }
298
- fromNow(now = LocalTime.now()) {
299
- const msDiff = LocalTime.of(now).unixMillis() - this.unixMillis();
322
+ fromNow(now = new Date()) {
323
+ const msDiff = LocalTime.parseToDate(now).valueOf() - this.$date.valueOf();
300
324
  if (msDiff === 0)
301
325
  return 'now';
302
326
  if (msDiff >= 0) {
@@ -408,4 +432,3 @@ function localTime(d) {
408
432
  return d ? LocalTime.of(d) : LocalTime.now();
409
433
  }
410
434
  exports.localTime = localTime;
411
- // todo: range
@@ -0,0 +1,38 @@
1
+ import { UnixTimestampNumber } from '../types';
2
+ import { Inclusiveness } from './localDate';
3
+ import { LocalTime, LocalTimeConfig } from './localTime';
4
+ export declare type TimeIntervalConfig = TimeInterval | TimeIntervalString;
5
+ export declare type TimeIntervalString = string;
6
+ /**
7
+ * Class that supports an "interval of time" between 2 timestamps - start and end.
8
+ * Example: `1649267185/1649267187`.
9
+ *
10
+ * @experimental
11
+ */
12
+ export declare class TimeInterval {
13
+ private $start;
14
+ private $end;
15
+ private constructor();
16
+ static of(start: LocalTimeConfig, end: LocalTimeConfig): TimeInterval;
17
+ get start(): UnixTimestampNumber;
18
+ get end(): UnixTimestampNumber;
19
+ get startTime(): LocalTime;
20
+ get endTime(): LocalTime;
21
+ /**
22
+ * Parses string like `1649267185/1649267187` into a TimeInterval.
23
+ */
24
+ static parse(d: TimeIntervalConfig): TimeInterval;
25
+ isSame(d: TimeIntervalConfig): boolean;
26
+ isBefore(d: TimeIntervalConfig, inclusive?: boolean): boolean;
27
+ isSameOrBefore(d: TimeIntervalConfig): boolean;
28
+ isAfter(d: TimeIntervalConfig, inclusive?: boolean): boolean;
29
+ isSameOrAfter(d: TimeIntervalConfig): boolean;
30
+ includes(d: LocalTimeConfig, incl?: Inclusiveness): boolean;
31
+ /**
32
+ * TimeIntervals compare by start date.
33
+ * If it's the same - then by end date.
34
+ */
35
+ cmp(d: TimeIntervalConfig): -1 | 0 | 1;
36
+ toString(): TimeIntervalString;
37
+ toJSON(): TimeIntervalString;
38
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TimeInterval = void 0;
4
+ const localTime_1 = require("./localTime");
5
+ /**
6
+ * Class that supports an "interval of time" between 2 timestamps - start and end.
7
+ * Example: `1649267185/1649267187`.
8
+ *
9
+ * @experimental
10
+ */
11
+ class TimeInterval {
12
+ constructor($start, $end) {
13
+ this.$start = $start;
14
+ this.$end = $end;
15
+ }
16
+ static of(start, end) {
17
+ return new TimeInterval(localTime_1.LocalTime.parseToUnixTimestamp(start), localTime_1.LocalTime.parseToUnixTimestamp(end));
18
+ }
19
+ get start() {
20
+ return this.$start;
21
+ }
22
+ get end() {
23
+ return this.$end;
24
+ }
25
+ get startTime() {
26
+ return localTime_1.LocalTime.of(this.$start);
27
+ }
28
+ get endTime() {
29
+ return localTime_1.LocalTime.of(this.$end);
30
+ }
31
+ /**
32
+ * Parses string like `1649267185/1649267187` into a TimeInterval.
33
+ */
34
+ static parse(d) {
35
+ if (d instanceof TimeInterval)
36
+ return d;
37
+ const [start, end] = d.split('/').map(Number);
38
+ if (!end || !start) {
39
+ throw new Error(`Cannot parse "${d}" into TimeInterval`);
40
+ }
41
+ return new TimeInterval(start, end);
42
+ }
43
+ isSame(d) {
44
+ return this.cmp(d) === 0;
45
+ }
46
+ isBefore(d, inclusive = false) {
47
+ const r = this.cmp(d);
48
+ return r === -1 || (r === 0 && inclusive);
49
+ }
50
+ isSameOrBefore(d) {
51
+ return this.cmp(d) <= 0;
52
+ }
53
+ isAfter(d, inclusive = false) {
54
+ const r = this.cmp(d);
55
+ return r === 1 || (r === 0 && inclusive);
56
+ }
57
+ isSameOrAfter(d) {
58
+ return this.cmp(d) >= 0;
59
+ }
60
+ includes(d, incl = '[)') {
61
+ d = localTime_1.LocalTime.parseToUnixTimestamp(d);
62
+ if (d < this.$start || (d === this.$start && incl[0] === '('))
63
+ return false;
64
+ if (d > this.$end || (d === this.$end && incl[1] === ')'))
65
+ return false;
66
+ return true;
67
+ }
68
+ /**
69
+ * TimeIntervals compare by start date.
70
+ * If it's the same - then by end date.
71
+ */
72
+ cmp(d) {
73
+ d = TimeInterval.parse(d);
74
+ if (this.$start > d.$start)
75
+ return 1;
76
+ if (this.$start < d.$start)
77
+ return -1;
78
+ if (this.$end > d.$end)
79
+ return 1;
80
+ if (this.$end < d.$end)
81
+ return -1;
82
+ return 0;
83
+ }
84
+ toString() {
85
+ return [this.$start, this.$end].join('/');
86
+ }
87
+ toJSON() {
88
+ return this.toString();
89
+ }
90
+ }
91
+ exports.TimeInterval = TimeInterval;
package/dist/index.d.ts CHANGED
@@ -51,7 +51,7 @@ export * from './string/string.util';
51
51
  import { JsonStringifyFunction, StringifyAnyOptions, _stringifyAny } from './string/stringifyAny';
52
52
  export * from './time/time.util';
53
53
  import { Class, ConditionalExcept, ConditionalPick, Merge, Promisable, ReadonlyDeep, Simplify } from './typeFest';
54
- import { AsyncMapper, AsyncPredicate, BaseDBEntity, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, Saved, Unsaved, BatchResult, InstanceId, IsoDate, IsoDateTime, KeyValueTuple, Mapper, ObjectMapper, ObjectPredicate, Predicate, PromiseMap, AnyObject, AnyFunction, Reviver, SavedDBEntity, StringMap, UnixTimestamp, Integer, ValueOf, ValuesOf, AbortableMapper, AbortableAsyncPredicate, AbortableAsyncMapper, AbortablePredicate, END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues } from './types';
54
+ import { AsyncMapper, AsyncPredicate, BaseDBEntity, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, Saved, Unsaved, BatchResult, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, KeyValueTuple, Mapper, ObjectMapper, ObjectPredicate, Predicate, PromiseMap, AnyObject, AnyFunction, Reviver, SavedDBEntity, StringMap, UnixTimestampNumber, UnixTimestamp, Integer, ValueOf, ValuesOf, AbortableMapper, AbortableAsyncPredicate, AbortableAsyncMapper, AbortablePredicate, END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues } from './types';
55
55
  export * from './unit/size.util';
56
56
  import { is } from './vendor/is';
57
57
  import { CommonLogLevel, CommonLogFunction, CommonLogger, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, CommonLogWithLevelFunction, commonLoggerCreate } from './log/commonLogger';
@@ -63,8 +63,10 @@ export * from './string/leven';
63
63
  export * from './datetime/localDate';
64
64
  export * from './datetime/localTime';
65
65
  export * from './datetime/dateInterval';
66
+ export * from './datetime/timeInterval';
66
67
  import { LocalDateConfig, LocalDateUnit, Inclusiveness } from './datetime/localDate';
67
68
  import { LocalTimeConfig, LocalTimeUnit, LocalTimeComponents } from './datetime/localTime';
68
69
  import { DateIntervalConfig, DateIntervalString } from './datetime/dateInterval';
69
- export type { DateIntervalConfig, DateIntervalString, LocalDateConfig, LocalDateUnit, Inclusiveness, LocalTimeConfig, LocalTimeUnit, LocalTimeComponents, AbortableMapper, AbortablePredicate, AbortableAsyncPredicate, AbortableAsyncMapper, PQueueCfg, MemoCache, AsyncMemoCache, PromiseDecoratorCfg, PromiseDecoratorResp, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse, Admin401ErrorData, Admin403ErrorData, StringMap, PromiseMap, AnyObject, AnyFunction, ValuesOf, ValueOf, KeyValueTuple, ObjectMapper, ObjectPredicate, InstanceId, IsoDate, IsoDateTime, Reviver, PMapOptions, Mapper, AsyncMapper, Predicate, AsyncPredicate, BatchResult, DeferredPromise, PRetryOptions, PTimeoutOptions, TryCatchOptions, StringifyAnyOptions, JsonStringifyFunction, Merge, ReadonlyDeep, Promisable, Simplify, ConditionalPick, ConditionalExcept, Class, UnixTimestamp, Integer, BaseDBEntity, SavedDBEntity, Saved, Unsaved, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, JsonSchema, JsonSchemaAny, JsonSchemaOneOf, JsonSchemaAllOf, JsonSchemaAnyOf, JsonSchemaNot, JsonSchemaRef, JsonSchemaConst, JsonSchemaEnum, JsonSchemaString, JsonSchemaNumber, JsonSchemaBoolean, JsonSchemaNull, JsonSchemaRootObject, JsonSchemaObject, JsonSchemaArray, JsonSchemaTuple, JsonSchemaBuilder, CommonLogLevel, CommonLogWithLevelFunction, CommonLogFunction, CommonLogger, };
70
+ import { TimeIntervalConfig, TimeIntervalString } from './datetime/timeInterval';
71
+ export type { DateIntervalConfig, DateIntervalString, TimeIntervalConfig, TimeIntervalString, LocalDateConfig, LocalDateUnit, Inclusiveness, LocalTimeConfig, LocalTimeUnit, LocalTimeComponents, AbortableMapper, AbortablePredicate, AbortableAsyncPredicate, AbortableAsyncMapper, PQueueCfg, MemoCache, AsyncMemoCache, PromiseDecoratorCfg, PromiseDecoratorResp, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse, Admin401ErrorData, Admin403ErrorData, StringMap, PromiseMap, AnyObject, AnyFunction, ValuesOf, ValueOf, KeyValueTuple, ObjectMapper, ObjectPredicate, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, Reviver, PMapOptions, Mapper, AsyncMapper, Predicate, AsyncPredicate, BatchResult, DeferredPromise, PRetryOptions, PTimeoutOptions, TryCatchOptions, StringifyAnyOptions, JsonStringifyFunction, Merge, ReadonlyDeep, Promisable, Simplify, ConditionalPick, ConditionalExcept, Class, UnixTimestampNumber, UnixTimestamp, Integer, BaseDBEntity, SavedDBEntity, Saved, Unsaved, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, JsonSchema, JsonSchemaAny, JsonSchemaOneOf, JsonSchemaAllOf, JsonSchemaAnyOf, JsonSchemaNot, JsonSchemaRef, JsonSchemaConst, JsonSchemaEnum, JsonSchemaString, JsonSchemaNumber, JsonSchemaBoolean, JsonSchemaNull, JsonSchemaRootObject, JsonSchemaObject, JsonSchemaArray, JsonSchemaTuple, JsonSchemaBuilder, CommonLogLevel, CommonLogWithLevelFunction, CommonLogFunction, CommonLogger, };
70
72
  export { is, _createPromiseDecorator, _stringMapValues, _stringMapEntries, _objectKeys, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, PQueue, END, SKIP, };
package/dist/index.js CHANGED
@@ -95,3 +95,4 @@ tslib_1.__exportStar(require("./string/leven"), exports);
95
95
  tslib_1.__exportStar(require("./datetime/localDate"), exports);
96
96
  tslib_1.__exportStar(require("./datetime/localTime"), exports);
97
97
  tslib_1.__exportStar(require("./datetime/dateInterval"), exports);
98
+ tslib_1.__exportStar(require("./datetime/timeInterval"), exports);
@@ -113,8 +113,8 @@ export declare class JsonSchemaObjectBuilder<T extends AnyObject> extends JsonSc
113
113
  minProps(minProperties: number): this;
114
114
  maxProps(maxProperties: number): this;
115
115
  additionalProps(additionalProperties: boolean): this;
116
- baseDBEntity<ID = string>(idType?: string): JsonSchemaObjectBuilder<T & BaseDBEntity<ID>>;
117
- savedDBEntity<ID = string>(idType?: string): JsonSchemaObjectBuilder<T & SavedDBEntity<ID>>;
116
+ baseDBEntity<ID extends string | number = string>(idType?: string): JsonSchemaObjectBuilder<T & BaseDBEntity<ID>>;
117
+ savedDBEntity<ID extends string | number = string>(idType?: string): JsonSchemaObjectBuilder<T & SavedDBEntity<ID>>;
118
118
  extend<T2 extends AnyObject>(s2: JsonSchemaObjectBuilder<T2>): JsonSchemaObjectBuilder<T & T2>;
119
119
  }
120
120
  export declare class JsonSchemaArrayBuilder<ITEM> extends JsonSchemaAnyBuilder<ITEM[], JsonSchemaArray<ITEM>> {
@@ -7,6 +7,10 @@
7
7
  * // 2.5
8
8
  */
9
9
  export declare function _average(values: number[]): number;
10
+ /**
11
+ * Same as _average, but safely returns null if input array is empty or nullish.
12
+ */
13
+ export declare function _averageOrNull(values: number[] | undefined | null): number | null;
10
14
  /**
11
15
  * valuesArray and weightsArray length is expected to be the same.
12
16
  */
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._median = exports._percentiles = exports._percentile = exports._averageWeighted = exports._average = void 0;
3
+ exports._median = exports._percentiles = exports._percentile = exports._averageWeighted = exports._averageOrNull = exports._average = void 0;
4
4
  const number_util_1 = require("../number/number.util");
5
5
  /**
6
6
  * @returns Average of the array of numbers
@@ -14,6 +14,13 @@ function _average(values) {
14
14
  return values.reduce((a, b) => a + b) / values.length;
15
15
  }
16
16
  exports._average = _average;
17
+ /**
18
+ * Same as _average, but safely returns null if input array is empty or nullish.
19
+ */
20
+ function _averageOrNull(values) {
21
+ return values?.length ? values.reduce((a, b) => a + b) / values.length : null;
22
+ }
23
+ exports._averageOrNull = _averageOrNull;
17
24
  /**
18
25
  * valuesArray and weightsArray length is expected to be the same.
19
26
  */
@@ -14,6 +14,10 @@ export declare class SimpleMovingAverage {
14
14
  * Returns 0 (not undefined) for empty data.
15
15
  */
16
16
  avg: number;
17
+ /**
18
+ * Push new value.
19
+ * Returns newly calculated average (using newly pushed value).
20
+ */
17
21
  push(n: number): number;
18
22
  private calculateAvg;
19
23
  }
package/dist/math/sma.js CHANGED
@@ -18,6 +18,10 @@ class SimpleMovingAverage {
18
18
  */
19
19
  this.avg = 0;
20
20
  }
21
+ /**
22
+ * Push new value.
23
+ * Returns newly calculated average (using newly pushed value).
24
+ */
21
25
  push(n) {
22
26
  this.data[this.nextIndex] = n;
23
27
  this.nextIndex =
package/dist/types.d.ts CHANGED
@@ -5,7 +5,7 @@ import { Merge, Promisable } from './typeFest';
5
5
  * Alternative: Record<string, T | undefined>
6
6
  */
7
7
  export interface StringMap<T = string> {
8
- [k: string]: T | undefined;
8
+ [k: string | number]: T | undefined;
9
9
  }
10
10
  /**
11
11
  * Object to be passed to pProps to resolve all promises into properties.
@@ -24,13 +24,13 @@ export interface CreatedUpdated {
24
24
  created: number;
25
25
  updated: number;
26
26
  }
27
- export interface CreatedUpdatedId<ID = string> extends CreatedUpdated {
27
+ export interface CreatedUpdatedId<ID extends string | number = string> extends CreatedUpdated {
28
28
  id: ID;
29
29
  }
30
- export interface ObjectWithId<ID = string> {
30
+ export interface ObjectWithId<ID extends string | number = string> {
31
31
  id: ID;
32
32
  }
33
- export interface AnyObjectWithId<ID = string> extends AnyObject, ObjectWithId<ID> {
33
+ export interface AnyObjectWithId<ID extends string | number = string> extends AnyObject, ObjectWithId<ID> {
34
34
  }
35
35
  /**
36
36
  * Convenience type shorthand.
@@ -111,18 +111,26 @@ export interface InstanceId {
111
111
  *
112
112
  * @example '2019-06-21'
113
113
  */
114
+ export declare type IsoDateString = string;
115
+ /**
116
+ * @deprecated use IsoDateString
117
+ */
114
118
  export declare type IsoDate = string;
115
119
  /**
116
120
  * Interface explicitly states that the value is an ISO DateTime string (with time).
117
121
  *
118
122
  * @example '2019-06-21T05:21:73Z'
119
123
  */
120
- export declare type IsoDateTime = string;
124
+ export declare type IsoDateTimeString = string;
121
125
  /**
122
126
  * Interface explicitly states that the value is a Unix timestamp (in seconds).
123
127
  *
124
128
  * @example 1628945450
125
129
  */
130
+ export declare type UnixTimestampNumber = number;
131
+ /**
132
+ * @deprecated use UnixTimestampNumber
133
+ */
126
134
  export declare type UnixTimestamp = number;
127
135
  /**
128
136
  * Same as `number`, but with semantic meaning that it's an Integer.
@@ -131,16 +139,16 @@ export declare type Integer = number;
131
139
  /**
132
140
  * Base interface for any Entity that was saved to DB.
133
141
  */
134
- export interface SavedDBEntity<ID = string> {
142
+ export interface SavedDBEntity<ID extends string | number = string> {
135
143
  id: ID;
136
144
  /**
137
145
  * unixTimestamp of when the entity was first created (in the DB).
138
146
  */
139
- created: UnixTimestamp;
147
+ created: UnixTimestampNumber;
140
148
  /**
141
149
  * unixTimestamp of when the entity was last updated (in the DB).
142
150
  */
143
- updated: UnixTimestamp;
151
+ updated: UnixTimestampNumber;
144
152
  }
145
153
  /**
146
154
  * Base interface for any Entity that can be saved to DB.
@@ -148,9 +156,9 @@ export interface SavedDBEntity<ID = string> {
148
156
  * hence `id`, `created` and `updated` fields CAN BE undefined (yet).
149
157
  * When it's known to be saved - `SavedDBEntity` interface can be used instead.
150
158
  */
151
- export declare type BaseDBEntity<ID = string> = Partial<SavedDBEntity<ID>>;
152
- export declare type Saved<E, ID = string> = Merge<E, SavedDBEntity<ID>>;
153
- export declare type Unsaved<E, ID = string> = Merge<E, BaseDBEntity<ID>>;
159
+ export declare type BaseDBEntity<ID extends string | number = string> = Partial<SavedDBEntity<ID>>;
160
+ export declare type Saved<E, ID extends string | number = string> = Merge<E, SavedDBEntity<ID>>;
161
+ export declare type Unsaved<E, ID extends string | number = string> = Merge<E, BaseDBEntity<ID>>;
154
162
  /**
155
163
  * Named type for JSON.parse / JSON.stringify second argument
156
164
  */
@@ -27,14 +27,16 @@ export class DateInterval {
27
27
  isSame(d) {
28
28
  return this.cmp(d) === 0;
29
29
  }
30
- isBefore(d) {
31
- return this.cmp(d) === -1;
30
+ isBefore(d, inclusive = false) {
31
+ const r = this.cmp(d);
32
+ return r === -1 || (r === 0 && inclusive);
32
33
  }
33
34
  isSameOrBefore(d) {
34
35
  return this.cmp(d) <= 0;
35
36
  }
36
- isAfter(d) {
37
- return this.cmp(d) === 1;
37
+ isAfter(d, inclusive = false) {
38
+ const r = this.cmp(d);
39
+ return r === 1 || (r === 0 && inclusive);
38
40
  }
39
41
  isSameOrAfter(d) {
40
42
  return this.cmp(d) >= 0;
@@ -42,9 +44,14 @@ export class DateInterval {
42
44
  /**
43
45
  * Ranges of DateInterval (start, end) are INCLUSIVE.
44
46
  */
45
- includes(d) {
47
+ includes(d, incl = '[]') {
46
48
  d = LocalDate.of(d);
47
- return d.isSameOrAfter(this.start) && d.isSameOrBefore(this.end);
49
+ return d.isAfter(this.start, incl[0] === '[') && d.isBefore(this.end, incl[1] === ']');
50
+ }
51
+ intersects(int, inclusive = true) {
52
+ const $int = DateInterval.parse(int);
53
+ const incl = inclusive ? '[]' : '()';
54
+ return this.includes($int.start, incl) || this.includes($int.end, incl);
48
55
  }
49
56
  /**
50
57
  * DateIntervals compare by start date.
@@ -54,18 +61,14 @@ export class DateInterval {
54
61
  d = DateInterval.parse(d);
55
62
  return this.start.cmp(d.start) || this.end.cmp(d.end);
56
63
  }
64
+ getDays(incl = '[]') {
65
+ return LocalDate.range(this.start, this.end, incl, 1, 'day');
66
+ }
57
67
  /**
58
68
  * Returns an array of LocalDates that are included in the interval.
59
- * Ranges are INCLUSIVE.
60
69
  */
61
- getDays() {
62
- const days = [];
63
- let current = this.start;
64
- do {
65
- days.push(current);
66
- current = current.add(1, 'day');
67
- } while (current.isSameOrBefore(this.end));
68
- return days;
70
+ range(incl = '[]', step = 1, stepUnit = 'day') {
71
+ return LocalDate.range(this.start, this.end, incl, step, stepUnit);
69
72
  }
70
73
  toString() {
71
74
  return [this.start, this.end].join('/');