@naturalcycles/js-lib 14.98.2 → 14.99.1

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.
@@ -137,7 +137,16 @@ export declare function _mapToObject<T, V>(array: T[], mapper: (item: T) => [key
137
137
  * Based on: https://stackoverflow.com/a/12646864/4919972
138
138
  */
139
139
  export declare function _shuffle<T>(array: T[], mutate?: boolean): T[];
140
+ /**
141
+ * Returns last item of non-empty array.
142
+ * Throws if array is empty.
143
+ */
144
+ export declare function _last<T>(array: T[]): T;
140
145
  /**
141
146
  * Returns last item of the array (or undefined if array is empty).
142
147
  */
143
- export declare function _last<T>(array: T[]): T | undefined;
148
+ export declare function _lastOrUndefined<T>(array: T[]): T | undefined;
149
+ export declare function _minOrUndefined<T>(array: T[]): T | undefined;
150
+ export declare function _min<T>(array: T[]): T;
151
+ export declare function _maxOrUndefined<T>(array: T[]): T | undefined;
152
+ export declare function _max<T>(array: T[]): T;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._last = exports._shuffle = exports._mapToObject = exports._sumBy = exports._sum = exports._difference = exports._intersection = exports._countBy = exports._dropRightWhile = exports._dropWhile = exports._takeRightWhile = exports._takeWhile = exports._findLast = exports._sortBy = exports._groupBy = exports._by = exports._uniqBy = exports._uniq = exports._flattenDeep = exports._flatten = exports._chunk = void 0;
3
+ exports._max = exports._maxOrUndefined = exports._min = exports._minOrUndefined = exports._lastOrUndefined = exports._last = exports._shuffle = exports._mapToObject = exports._sumBy = exports._sum = exports._difference = exports._intersection = exports._countBy = exports._dropRightWhile = exports._dropWhile = exports._takeRightWhile = exports._takeWhile = exports._findLast = exports._sortBy = exports._groupBy = exports._by = exports._uniqBy = exports._uniq = exports._flattenDeep = exports._flatten = exports._chunk = void 0;
4
4
  /**
5
5
  * Creates an array of elements split into groups the length of size. If collection can’t be split evenly, the
6
6
  * final chunk will be the remaining elements.
@@ -260,9 +260,43 @@ function _shuffle(array, mutate = false) {
260
260
  }
261
261
  exports._shuffle = _shuffle;
262
262
  /**
263
- * Returns last item of the array (or undefined if array is empty).
263
+ * Returns last item of non-empty array.
264
+ * Throws if array is empty.
264
265
  */
265
266
  function _last(array) {
267
+ if (!array.length)
268
+ throw new Error('_last called on empty array');
266
269
  return array[array.length - 1];
267
270
  }
268
271
  exports._last = _last;
272
+ /**
273
+ * Returns last item of the array (or undefined if array is empty).
274
+ */
275
+ function _lastOrUndefined(array) {
276
+ return array[array.length - 1];
277
+ }
278
+ exports._lastOrUndefined = _lastOrUndefined;
279
+ function _minOrUndefined(array) {
280
+ if (!array.length)
281
+ return;
282
+ return _min(array);
283
+ }
284
+ exports._minOrUndefined = _minOrUndefined;
285
+ function _min(array) {
286
+ if (!array.length)
287
+ throw new Error('_min called on empty array');
288
+ return array.reduce((min, item) => (min <= item ? min : item));
289
+ }
290
+ exports._min = _min;
291
+ function _maxOrUndefined(array) {
292
+ if (!array.length)
293
+ return;
294
+ return _max(array);
295
+ }
296
+ exports._maxOrUndefined = _maxOrUndefined;
297
+ function _max(array) {
298
+ if (!array.length)
299
+ throw new Error('_max called on empty array');
300
+ return array.reduce((max, item) => (max >= item ? max : item));
301
+ }
302
+ exports._max = _max;
@@ -1,8 +1,10 @@
1
- import { IsoDateString, UnixTimestampNumber } from '../types';
1
+ import { IsoDateString, IsoDateTimeString, UnixTimestampNumber } from '../types';
2
2
  import { LocalTime } from './localTime';
3
- export declare type LocalDateUnit = 'year' | 'month' | 'day';
3
+ export declare type LocalDateUnit = LocalDateUnitStrict | 'week';
4
+ export declare type LocalDateUnitStrict = 'year' | 'month' | 'day';
4
5
  export declare type Inclusiveness = '()' | '[]' | '[)' | '(]';
5
6
  export declare type LocalDateConfig = LocalDate | IsoDateString;
7
+ export declare type LocalDateFormatter = (ld: LocalDate) => string;
6
8
  /**
7
9
  * @experimental
8
10
  */
@@ -28,13 +30,13 @@ export declare class LocalDate {
28
30
  static today(): LocalDate;
29
31
  static todayUTC(): LocalDate;
30
32
  static sort(items: LocalDate[], mutate?: boolean, descending?: boolean): LocalDate[];
31
- static earliestOrUndefined(items: LocalDate[]): LocalDate | undefined;
32
- static earliest(items: LocalDate[]): LocalDate;
33
- static latestOrUndefined(items: LocalDate[]): LocalDate | undefined;
34
- static latest(items: LocalDate[]): LocalDate;
33
+ static earliestOrUndefined(items: LocalDateConfig[]): LocalDate | undefined;
34
+ static earliest(items: LocalDateConfig[]): LocalDate;
35
+ static latestOrUndefined(items: LocalDateConfig[]): LocalDate | undefined;
36
+ static latest(items: LocalDateConfig[]): LocalDate;
35
37
  static range(min: LocalDateConfig, max: LocalDateConfig, incl?: Inclusiveness, step?: number, stepUnit?: LocalDateUnit): LocalDate[];
36
- get(unit: LocalDateUnit): number;
37
- set(unit: LocalDateUnit, v: number, mutate?: boolean): LocalDate;
38
+ get(unit: LocalDateUnitStrict): number;
39
+ set(unit: LocalDateUnitStrict, v: number, mutate?: boolean): LocalDate;
38
40
  year(): number;
39
41
  year(v: number): LocalDate;
40
42
  month(): number;
@@ -58,15 +60,15 @@ export declare class LocalDate {
58
60
  */
59
61
  absDiff(d: LocalDateConfig, unit: LocalDateUnit): number;
60
62
  /**
61
- * Returns the number of **full** units difference (aka `Math.ceil`).
63
+ * Returns the number of **full** units difference (aka `Math.floor`).
62
64
  *
63
65
  * a.diff(b) means "a minus b"
64
66
  */
65
67
  diff(d: LocalDateConfig, unit: LocalDateUnit): number;
66
68
  add(num: number, unit: LocalDateUnit, mutate?: boolean): LocalDate;
67
69
  subtract(num: number, unit: LocalDateUnit, mutate?: boolean): LocalDate;
68
- startOf(unit: LocalDateUnit): LocalDate;
69
- endOf(unit: LocalDateUnit): LocalDate;
70
+ startOf(unit: LocalDateUnitStrict): LocalDate;
71
+ endOf(unit: LocalDateUnitStrict): LocalDate;
70
72
  static getYearLength(year: number): number;
71
73
  static getMonthLength(year: number, month: number): number;
72
74
  static isLeapYear(year: number): boolean;
@@ -80,11 +82,16 @@ export declare class LocalDate {
80
82
  toDate(): Date;
81
83
  toLocalTime(): LocalTime;
82
84
  toISODate(): IsoDateString;
85
+ /**
86
+ * Returns e.g: `1984-06-21T17:56:21`
87
+ */
88
+ toISODateTime(): IsoDateTimeString;
83
89
  toString(): IsoDateString;
84
90
  toStringCompact(): string;
85
91
  unix(): UnixTimestampNumber;
86
92
  unixMillis(): number;
87
93
  toJSON(): IsoDateString;
94
+ format(fmt: LocalDateFormatter): string;
88
95
  }
89
96
  /**
90
97
  * Shortcut wrapper around `LocalDate.parse` / `LocalDate.today`
@@ -90,16 +90,24 @@ class LocalDate {
90
90
  }
91
91
  static earliest(items) {
92
92
  (0, assert_1._assert)(items.length, 'LocalDate.earliest called on empty array');
93
- return items.reduce((min, item) => (min.isSameOrBefore(item) ? min : item));
93
+ return items
94
+ .map(i => LocalDate.of(i))
95
+ .reduce((min, item) => (min.isSameOrBefore(item) ? min : item));
94
96
  }
95
97
  static latestOrUndefined(items) {
96
98
  return items.length ? LocalDate.latest(items) : undefined;
97
99
  }
98
100
  static latest(items) {
99
101
  (0, assert_1._assert)(items.length, 'LocalDate.latest called on empty array');
100
- return items.reduce((max, item) => (max.isSameOrAfter(item) ? max : item));
102
+ return items
103
+ .map(i => LocalDate.of(i))
104
+ .reduce((max, item) => (max.isSameOrAfter(item) ? max : item));
101
105
  }
102
106
  static range(min, max, incl = '[)', step = 1, stepUnit = 'day') {
107
+ if (stepUnit === 'week') {
108
+ step *= 7;
109
+ stepUnit = 'day';
110
+ }
103
111
  const dates = [];
104
112
  const $min = LocalDate.of(min);
105
113
  const $max = LocalDate.of(max).startOf(stepUnit);
@@ -197,44 +205,58 @@ class LocalDate {
197
205
  return Math.abs(this.diff(d, unit));
198
206
  }
199
207
  /**
200
- * Returns the number of **full** units difference (aka `Math.ceil`).
208
+ * Returns the number of **full** units difference (aka `Math.floor`).
201
209
  *
202
210
  * a.diff(b) means "a minus b"
203
211
  */
204
212
  diff(d, unit) {
205
213
  d = LocalDate.of(d);
214
+ const sign = this.cmp(d);
215
+ if (!sign)
216
+ return 0;
217
+ // Put items in descending order: "big minus small"
218
+ const [big, small] = sign === 1 ? [this, d] : [d, this];
206
219
  if (unit === 'year') {
207
- return this.$year - d.$year;
220
+ let years = big.$year - small.$year;
221
+ if (big.$month < small.$month || (big.$month === small.$month && big.$day < small.$day)) {
222
+ years--;
223
+ }
224
+ return years * sign || 0;
208
225
  }
209
226
  if (unit === 'month') {
210
- return (this.$year - d.$year) * 12 + (this.$month - d.$month);
227
+ let months = (big.$year - small.$year) * 12 + (big.$month - small.$month);
228
+ if (big.$day < small.$day)
229
+ months--;
230
+ return months * sign || 0;
211
231
  }
212
- // unit is 'day'
213
- let days = this.$day - d.$day;
214
- if (d.$year < this.$year) {
215
- for (let year = d.$year; year < this.$year; year++) {
216
- days += LocalDate.getYearLength(year);
217
- }
232
+ // unit is 'day' or 'week'
233
+ let days = big.$day - small.$day;
234
+ // If small date is after 1st of March - next year's "leapness" should be used
235
+ const offsetYear = small.$month >= 3 ? 1 : 0;
236
+ for (let year = small.$year; year < big.$year; year++) {
237
+ days += LocalDate.getYearLength(year + offsetYear);
218
238
  }
219
- else if (this.$year < d.$year) {
220
- for (let year = this.$year; year < d.$year; year++) {
221
- days -= LocalDate.getYearLength(year);
239
+ if (small.$month < big.$month) {
240
+ for (let month = small.$month; month < big.$month; month++) {
241
+ days += LocalDate.getMonthLength(big.$year, month);
222
242
  }
223
243
  }
224
- if (d.$month < this.$month) {
225
- for (let month = d.$month; month < this.$month; month++) {
226
- days += LocalDate.getMonthLength(this.$year, month);
244
+ else if (big.$month < small.$month) {
245
+ for (let month = big.$month; month < small.$month; month++) {
246
+ days -= LocalDate.getMonthLength(big.$year, month);
227
247
  }
228
248
  }
229
- else if (this.$month < d.$month) {
230
- for (let month = this.$month; month < d.$month; month++) {
231
- days -= LocalDate.getMonthLength(d.$year, month);
232
- }
249
+ if (unit === 'week') {
250
+ return Math.trunc(days / 7) * sign || 0;
233
251
  }
234
- return days;
252
+ return days * sign || 0;
235
253
  }
236
254
  add(num, unit, mutate = false) {
237
255
  let { $day, $month, $year } = this;
256
+ if (unit === 'week') {
257
+ num *= 7;
258
+ unit = 'day';
259
+ }
238
260
  if (unit === 'day') {
239
261
  $day += num;
240
262
  }
@@ -334,6 +356,12 @@ class LocalDate {
334
356
  toISODate() {
335
357
  return this.toString();
336
358
  }
359
+ /**
360
+ * Returns e.g: `1984-06-21T17:56:21`
361
+ */
362
+ toISODateTime() {
363
+ return this.toString() + 'T00:00:00';
364
+ }
337
365
  toString() {
338
366
  return [
339
367
  String(this.$year).padStart(4, '0'),
@@ -358,6 +386,9 @@ class LocalDate {
358
386
  toJSON() {
359
387
  return this.toString();
360
388
  }
389
+ format(fmt) {
390
+ return fmt(this);
391
+ }
361
392
  }
362
393
  exports.LocalDate = LocalDate;
363
394
  /**
@@ -1,7 +1,17 @@
1
1
  import { IsoDateString, IsoDateTimeString, UnixTimestampNumber } from '../types';
2
2
  import { Inclusiveness, LocalDate } from './localDate';
3
- export declare type LocalTimeUnit = 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second';
3
+ export declare type LocalTimeUnit = 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second';
4
+ export declare enum ISODayOfWeek {
5
+ MONDAY = 1,
6
+ TUESDAY = 2,
7
+ WEDNESDAY = 3,
8
+ THURSDAY = 4,
9
+ FRIDAY = 5,
10
+ SATURDAY = 6,
11
+ SUNDAY = 7
12
+ }
4
13
  export declare type LocalTimeConfig = LocalTime | Date | IsoDateTimeString | UnixTimestampNumber;
14
+ export declare type LocalTimeFormatter = (ld: LocalTime) => string;
5
15
  export interface LocalTimeComponents {
6
16
  year: number;
7
17
  month: number;
@@ -42,8 +52,15 @@ export declare class LocalTime {
42
52
  year(v: number): LocalTime;
43
53
  month(): number;
44
54
  month(v: number): LocalTime;
55
+ week(): number;
56
+ week(v: number): LocalTime;
45
57
  day(): number;
46
58
  day(v: number): LocalTime;
59
+ /**
60
+ * Based on ISO: 1-7 is Mon-Sun.
61
+ */
62
+ dayOfWeek(): ISODayOfWeek;
63
+ dayOfWeek(v: ISODayOfWeek): LocalTime;
47
64
  hour(): number;
48
65
  hour(v: number): LocalTime;
49
66
  minute(): number;
@@ -56,11 +73,12 @@ export declare class LocalTime {
56
73
  absDiff(other: LocalTimeConfig, unit: LocalTimeUnit): number;
57
74
  diff(other: LocalTimeConfig, unit: LocalTimeUnit): number;
58
75
  startOf(unit: LocalTimeUnit, mutate?: boolean): LocalTime;
76
+ endOf(unit: LocalTimeUnit, mutate?: boolean): LocalTime;
59
77
  static sort(items: LocalTime[], mutate?: boolean, descending?: boolean): LocalTime[];
60
- static earliestOrUndefined(items: LocalTime[]): LocalTime | undefined;
61
- static earliest(items: LocalTime[]): LocalTime;
62
- static latestOrUndefined(items: LocalTime[]): LocalTime | undefined;
63
- static latest(items: LocalTime[]): LocalTime;
78
+ static earliestOrUndefined(items: LocalTimeConfig[]): LocalTime | undefined;
79
+ static earliest(items: LocalTimeConfig[]): LocalTime;
80
+ static latestOrUndefined(items: LocalTimeConfig[]): LocalTime | undefined;
81
+ static latest(items: LocalTimeConfig[]): LocalTime;
64
82
  isSame(d: LocalTimeConfig): boolean;
65
83
  isBefore(d: LocalTimeConfig, inclusive?: boolean): boolean;
66
84
  isSameOrBefore(d: LocalTimeConfig): boolean;
@@ -83,7 +101,7 @@ export declare class LocalTime {
83
101
  toLocalDate(): LocalDate;
84
102
  toPretty(seconds?: boolean): IsoDateTimeString;
85
103
  /**
86
- * Returns e.g: `1984-06-21T17:56:21`, only the date part of DateTime
104
+ * Returns e.g: `1984-06-21T17:56:21`
87
105
  */
88
106
  toISODateTime(): IsoDateTimeString;
89
107
  /**
@@ -100,6 +118,7 @@ export declare class LocalTime {
100
118
  toStringCompact(seconds?: boolean): string;
101
119
  toString(): string;
102
120
  toJSON(): UnixTimestampNumber;
121
+ format(fmt: LocalTimeFormatter): string;
103
122
  }
104
123
  /**
105
124
  * Shortcut wrapper around `LocalDate.parse` / `LocalDate.today`
@@ -1,9 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.localTime = exports.LocalTime = void 0;
3
+ exports.localTime = exports.LocalTime = exports.ISODayOfWeek = void 0;
4
4
  const assert_1 = require("../error/assert");
5
5
  const time_util_1 = require("../time/time.util");
6
6
  const localDate_1 = require("./localDate");
7
+ var ISODayOfWeek;
8
+ (function (ISODayOfWeek) {
9
+ ISODayOfWeek[ISODayOfWeek["MONDAY"] = 1] = "MONDAY";
10
+ ISODayOfWeek[ISODayOfWeek["TUESDAY"] = 2] = "TUESDAY";
11
+ ISODayOfWeek[ISODayOfWeek["WEDNESDAY"] = 3] = "WEDNESDAY";
12
+ ISODayOfWeek[ISODayOfWeek["THURSDAY"] = 4] = "THURSDAY";
13
+ ISODayOfWeek[ISODayOfWeek["FRIDAY"] = 5] = "FRIDAY";
14
+ ISODayOfWeek[ISODayOfWeek["SATURDAY"] = 6] = "SATURDAY";
15
+ ISODayOfWeek[ISODayOfWeek["SUNDAY"] = 7] = "SUNDAY";
16
+ })(ISODayOfWeek = exports.ISODayOfWeek || (exports.ISODayOfWeek = {}));
17
+ const weekStartsOn = 1; // mon, as per ISO
18
+ const MILLISECONDS_IN_WEEK = 604800000;
19
+ const SECONDS_IN_DAY = 86400;
20
+ // const MILLISECONDS_IN_DAY = 86400000
21
+ // const MILLISECONDS_IN_MINUTE = 60000
22
+ const VALID_DAYS_OF_WEEK = new Set([1, 2, 3, 4, 5, 6, 7]);
7
23
  /* eslint-disable no-dupe-class-members */
8
24
  /**
9
25
  * @experimental
@@ -107,6 +123,9 @@ class LocalTime {
107
123
  if (unit === 'minute') {
108
124
  return this.utcMode ? this.$date.getUTCMinutes() : this.$date.getMinutes();
109
125
  }
126
+ if (unit === 'week') {
127
+ return getWeek(this.$date);
128
+ }
110
129
  // second
111
130
  return this.utcMode ? this.$date.getUTCSeconds() : this.$date.getSeconds();
112
131
  }
@@ -131,6 +150,9 @@ class LocalTime {
131
150
  else if (unit === 'second') {
132
151
  this.utcMode ? t.$date.setUTCSeconds(v) : t.$date.setSeconds(v);
133
152
  }
153
+ else if (unit === 'week') {
154
+ setWeek(t.$date, v, true);
155
+ }
134
156
  /* eslint-enable @typescript-eslint/no-unused-expressions */
135
157
  return t;
136
158
  }
@@ -140,9 +162,21 @@ class LocalTime {
140
162
  month(v) {
141
163
  return v === undefined ? this.get('month') : this.set('month', v);
142
164
  }
165
+ week(v) {
166
+ return v === undefined ? getWeek(this.$date) : this.set('week', v);
167
+ }
143
168
  day(v) {
144
169
  return v === undefined ? this.get('day') : this.set('day', v);
145
170
  }
171
+ dayOfWeek(v) {
172
+ const dow = (this.$date.getDay() || 7);
173
+ if (v === undefined) {
174
+ return dow;
175
+ }
176
+ if (!VALID_DAYS_OF_WEEK.has(v))
177
+ throw new Error(`Invalid dayOfWeek: ${v}`);
178
+ return this.add(v - dow, 'day');
179
+ }
146
180
  hour(v) {
147
181
  return v === undefined ? this.get('hour') : this.set('hour', v);
148
182
  }
@@ -177,6 +211,10 @@ class LocalTime {
177
211
  return mutate ? this : new LocalTime(d, this.utcMode);
178
212
  }
179
213
  add(num, unit, mutate = false) {
214
+ if (unit === 'week') {
215
+ num *= 7;
216
+ unit = 'day';
217
+ }
180
218
  return this.set(unit, this.get(unit) + num, mutate);
181
219
  }
182
220
  subtract(num, unit, mutate = false) {
@@ -187,21 +225,43 @@ class LocalTime {
187
225
  }
188
226
  diff(other, unit) {
189
227
  const date2 = LocalTime.parseToDate(other);
190
- if (unit === 'year') {
191
- return this.$date.getFullYear() - date2.getFullYear();
192
- }
193
- if (unit === 'month') {
194
- return ((this.$date.getFullYear() - date2.getFullYear()) * 12 +
195
- this.$date.getMonth() -
196
- date2.getMonth());
197
- }
198
228
  const secDiff = (this.$date.valueOf() - date2.valueOf()) / 1000;
229
+ if (!secDiff)
230
+ return 0;
231
+ if (unit === 'year' || unit === 'month') {
232
+ const sign = secDiff > 0 ? 1 : -1;
233
+ // Put items in descending order: "big minus small"
234
+ const [big, small] = sign === 1 ? [this.$date, date2] : [date2, this.$date];
235
+ if (unit === 'year') {
236
+ let years = big.getFullYear() - small.getFullYear();
237
+ const big2 = new Date(big);
238
+ const small2 = new Date(small);
239
+ big2.setFullYear(1584);
240
+ small2.setFullYear(1584);
241
+ if (big2 < small2)
242
+ years--;
243
+ return years * sign || 0;
244
+ }
245
+ if (unit === 'month') {
246
+ let months = (big.getFullYear() - small.getFullYear()) * 12 + big.getMonth() - small.getMonth();
247
+ const big2 = new Date(big);
248
+ const small2 = new Date(small);
249
+ big2.setFullYear(1584, 0);
250
+ small2.setFullYear(1584, 0);
251
+ if (big2 < small2)
252
+ months--;
253
+ return months * sign || 0;
254
+ }
255
+ }
199
256
  let r;
200
257
  if (unit === 'day') {
201
- r = secDiff / (24 * 60 * 60);
258
+ r = secDiff / SECONDS_IN_DAY;
259
+ }
260
+ else if (unit === 'week') {
261
+ r = secDiff / (7 * 24 * 60 * 60);
202
262
  }
203
263
  else if (unit === 'hour') {
204
- r = secDiff / (60 * 60);
264
+ r = secDiff / 3600;
205
265
  }
206
266
  else if (unit === 'minute') {
207
267
  r = secDiff / 60;
@@ -210,25 +270,60 @@ class LocalTime {
210
270
  // unit === 'second'
211
271
  r = secDiff;
212
272
  }
213
- r = r < 0 ? -Math.floor(-r) : Math.floor(r);
214
- if (Object.is(r, -0))
215
- return 0;
216
- return r;
273
+ // `|| 0` is to avoid returning -0
274
+ return Math.trunc(r) || 0;
217
275
  }
218
276
  startOf(unit, mutate = false) {
219
277
  if (unit === 'second')
220
278
  return this;
221
279
  const d = mutate ? this.$date : new Date(this.$date);
280
+ d.setSeconds(0, 0);
222
281
  /* eslint-disable @typescript-eslint/no-unused-expressions */
223
- this.utcMode ? d.setUTCSeconds(0) : d.setSeconds(0);
224
282
  if (unit !== 'minute') {
225
283
  this.utcMode ? d.setUTCMinutes(0) : d.setMinutes(0);
226
284
  if (unit !== 'hour') {
227
285
  this.utcMode ? d.setUTCHours(0) : d.setHours(0);
228
286
  if (unit !== 'day') {
229
- this.utcMode ? d.setUTCDate(0) : d.setDate(0);
230
- if (unit !== 'month') {
287
+ // year, month or week
288
+ if (unit === 'year') {
231
289
  this.utcMode ? d.setUTCMonth(0) : d.setMonth(0);
290
+ this.utcMode ? d.setUTCDate(1) : d.setDate(1);
291
+ }
292
+ else if (unit === 'month') {
293
+ this.utcMode ? d.setUTCDate(1) : d.setDate(1);
294
+ }
295
+ else {
296
+ // week
297
+ startOfWeek(d, true);
298
+ }
299
+ }
300
+ }
301
+ }
302
+ /* eslint-enable @typescript-eslint/no-unused-expressions */
303
+ return mutate ? this : new LocalTime(d, this.utcMode);
304
+ }
305
+ endOf(unit, mutate = false) {
306
+ if (unit === 'second')
307
+ return this;
308
+ const d = mutate ? this.$date : new Date(this.$date);
309
+ d.setSeconds(59, 0);
310
+ /* eslint-disable @typescript-eslint/no-unused-expressions */
311
+ if (unit !== 'minute') {
312
+ this.utcMode ? d.setUTCMinutes(59) : d.setMinutes(59);
313
+ if (unit !== 'hour') {
314
+ this.utcMode ? d.setUTCHours(23) : d.setHours(23);
315
+ if (unit !== 'day') {
316
+ // year, month or week
317
+ if (unit === 'year') {
318
+ this.utcMode ? d.setUTCMonth(11) : d.setMonth(11);
319
+ }
320
+ if (unit === 'week') {
321
+ endOfWeek(d, true);
322
+ }
323
+ else {
324
+ // year or month
325
+ const lastDay = localDate_1.LocalDate.getMonthLength(d.getFullYear(), d.getMonth() + 1);
326
+ this.utcMode ? d.setUTCDate(lastDay) : d.setDate(lastDay);
232
327
  }
233
328
  }
234
329
  }
@@ -251,14 +346,18 @@ class LocalTime {
251
346
  }
252
347
  static earliest(items) {
253
348
  (0, assert_1._assert)(items.length, 'LocalTime.earliest called on empty array');
254
- return items.reduce((min, item) => (min.isSameOrBefore(item) ? min : item));
349
+ return items
350
+ .map(i => LocalTime.of(i))
351
+ .reduce((min, item) => (min.isSameOrBefore(item) ? min : item));
255
352
  }
256
353
  static latestOrUndefined(items) {
257
354
  return items.length ? LocalTime.latest(items) : undefined;
258
355
  }
259
356
  static latest(items) {
260
357
  (0, assert_1._assert)(items.length, 'LocalTime.latest called on empty array');
261
- return items.reduce((max, item) => (max.isSameOrAfter(item) ? max : item));
358
+ return items
359
+ .map(i => LocalTime.of(i))
360
+ .reduce((max, item) => (max.isSameOrAfter(item) ? max : item));
262
361
  }
263
362
  isSame(d) {
264
363
  return this.cmp(d) === 0;
@@ -298,7 +397,6 @@ class LocalTime {
298
397
  return 0;
299
398
  return t1 < t2 ? -1 : 1;
300
399
  }
301
- // todo: endOf
302
400
  components() {
303
401
  if (this.utcMode) {
304
402
  return {
@@ -371,7 +469,7 @@ class LocalTime {
371
469
  // .join(' ')
372
470
  }
373
471
  /**
374
- * Returns e.g: `1984-06-21T17:56:21`, only the date part of DateTime
472
+ * Returns e.g: `1984-06-21T17:56:21`
375
473
  */
376
474
  toISODateTime() {
377
475
  return this.$date.toISOString().slice(0, 19);
@@ -423,6 +521,9 @@ class LocalTime {
423
521
  toJSON() {
424
522
  return this.unix();
425
523
  }
524
+ format(fmt) {
525
+ return fmt(this);
526
+ }
426
527
  }
427
528
  exports.LocalTime = LocalTime;
428
529
  /**
@@ -432,3 +533,83 @@ function localTime(d) {
432
533
  return d ? LocalTime.of(d) : LocalTime.now();
433
534
  }
434
535
  exports.localTime = localTime;
536
+ // based on: https://github.com/date-fns/date-fns/blob/master/src/getISOWeek/index.ts
537
+ function getWeek(date) {
538
+ const diff = startOfWeek(date).getTime() - startOfWeekYear(date).getTime();
539
+ return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
540
+ }
541
+ function setWeek(date, week, mutate = false) {
542
+ const d = mutate ? date : new Date(date);
543
+ const diff = getWeek(d) - week;
544
+ d.setDate(d.getDate() - diff * 7);
545
+ return d;
546
+ }
547
+ // based on: https://github.com/date-fns/date-fns/blob/master/src/startOfISOWeekYear/index.ts
548
+ function startOfWeekYear(date) {
549
+ const year = getWeekYear(date);
550
+ const fourthOfJanuary = new Date(0);
551
+ fourthOfJanuary.setFullYear(year, 0, 4);
552
+ fourthOfJanuary.setHours(0, 0, 0, 0);
553
+ return startOfWeek(fourthOfJanuary, true);
554
+ }
555
+ // based on: https://github.com/date-fns/date-fns/blob/fd6bb1a0bab143f2da068c05a9c562b9bee1357d/src/getISOWeekYear/index.ts
556
+ function getWeekYear(date) {
557
+ const year = date.getFullYear();
558
+ const fourthOfJanuaryOfNextYear = new Date(0);
559
+ fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
560
+ fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
561
+ const startOfNextYear = startOfWeek(fourthOfJanuaryOfNextYear, true);
562
+ const fourthOfJanuaryOfThisYear = new Date(0);
563
+ fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
564
+ fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
565
+ const startOfThisYear = startOfWeek(fourthOfJanuaryOfThisYear, true);
566
+ if (date.getTime() >= startOfNextYear.getTime()) {
567
+ return year + 1;
568
+ }
569
+ else if (date.getTime() >= startOfThisYear.getTime()) {
570
+ return year;
571
+ }
572
+ else {
573
+ return year - 1;
574
+ }
575
+ }
576
+ // function setWeekYear(
577
+ // date: Date,
578
+ // year: number,
579
+ // ): Date {
580
+ // const diff = differenceInCalendarDays(date, startOfWeekYear(date))
581
+ // const fourthOfJanuary = new Date(0)
582
+ // fourthOfJanuary.setFullYear(year, 0, 4)
583
+ // fourthOfJanuary.setHours(0, 0, 0, 0)
584
+ // date = startOfWeekYear(fourthOfJanuary)
585
+ // date.setDate(date.getDate() + diff)
586
+ // return date
587
+ // }
588
+ // function differenceInCalendarDays(
589
+ // dateLeft: Date,
590
+ // dateRight: Date,
591
+ // ): number {
592
+ // return Math.round((startOfDay(dateLeft).getTime() - startOfDay(dateRight).getTime()) / MILLISECONDS_IN_DAY)
593
+ // }
594
+ // function startOfDay(date: Date, mutate = false): Date {
595
+ // const d = mutate ? date : new Date(date)
596
+ // d.setHours(0, 0, 0, 0)
597
+ // return d
598
+ // }
599
+ // based on: https://github.com/date-fns/date-fns/blob/fd6bb1a0bab143f2da068c05a9c562b9bee1357d/src/startOfWeek/index.ts
600
+ function startOfWeek(date, mutate = false) {
601
+ const d = mutate ? date : new Date(date);
602
+ const day = d.getDay();
603
+ const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
604
+ d.setDate(d.getDate() - diff);
605
+ d.setHours(0, 0, 0, 0);
606
+ return d;
607
+ }
608
+ // based on: https://github.com/date-fns/date-fns/blob/master/src/endOfWeek/index.ts
609
+ function endOfWeek(date, mutate = false) {
610
+ const d = mutate ? date : new Date(date);
611
+ const day = d.getDay();
612
+ const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
613
+ d.setDate(d.getDate() + diff);
614
+ return d;
615
+ }