@tim-code/my-util 0.0.2 → 0.0.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tim-code/my-util",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "author": "",
package/src/array.js CHANGED
@@ -27,3 +27,84 @@ export function chunk(array, chunkSize = array.length) {
27
27
  export function unique(array) {
28
28
  return [...new Set(array)]
29
29
  }
30
+
31
+ /**
32
+ * Mutates the passed in object by calling callback on each of its values.
33
+ * @param {Object} object
34
+ * @param {Function} callback (value, key, object) => newValue // note if not changing value, should return value
35
+ * @returns {Object}
36
+ */
37
+ export function mutateValues(object, callback) {
38
+ for (const key in object) {
39
+ object[key] = callback(object[key], key, object)
40
+ }
41
+ return object
42
+ }
43
+
44
+ // sorts undefined and null to the end if applicable
45
+ function compareUndefinedNull(a, b) {
46
+ if (b === undefined || b === null) {
47
+ if (a === undefined || a === null) {
48
+ return 0
49
+ }
50
+ return -1
51
+ } else if (a === undefined || a === null) {
52
+ return 1
53
+ }
54
+ return undefined
55
+ }
56
+
57
+ /**
58
+ * Returns an "ascending" comparator, via "<", to be used to sort an array.
59
+ * Undefined or null values are always sorted to the end.
60
+ * @param {String=} key If sorting objects, can specify a key to use to compare.
61
+ * @returns {Function}
62
+ */
63
+ export function ascending(key) {
64
+ if (!key) {
65
+ return (a, b) => {
66
+ return compareUndefinedNull(a, b) ?? (a < b ? -1 : b < a ? 1 : 0)
67
+ }
68
+ }
69
+ return (a, b) => {
70
+ return (
71
+ compareUndefinedNull(a[key], b[key]) ?? (a[key] < b[key] ? -1 : b[key] < a[key] ? 1 : 0)
72
+ )
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Returns a "descending" comparator, via ">", to be used to sort an array.
78
+ * Undefined or null values are always sorted to the end.
79
+ * @param {String=} key If sorting objects, can specify a key to use to compare.
80
+ * @returns {Function}
81
+ */
82
+ export function descending(key) {
83
+ if (!key) {
84
+ return (a, b) => {
85
+ return compareUndefinedNull(a, b) ?? (a > b ? -1 : b > a ? 1 : 0)
86
+ }
87
+ }
88
+ return (a, b) => {
89
+ return (
90
+ compareUndefinedNull(a[key], b[key]) ?? (a[key] > b[key] ? -1 : b[key] > a[key] ? 1 : 0)
91
+ )
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Parse an integer in base 10. Safe to use for array.map() since it only takes one argument and ignores the rest.
97
+ * @param {string} number
98
+ * @returns {number} Integer
99
+ */
100
+ export function parseIntSafe(number) {
101
+ return parseInt(number, 10)
102
+ }
103
+
104
+ // not sure how far we want to go down "key" rabbit hole:
105
+ // export function sum(array, key) {}
106
+ // or maybe
107
+ // export function add(key) {
108
+ // if(!key) return (acc, value) => acc + value
109
+ // return (acc, obj) => acc + obj[key]
110
+ // }
package/src/array.test.js CHANGED
@@ -1,7 +1,7 @@
1
- // src/array.test.js
2
- import { describe, expect, it } from "@jest/globals"
1
+ /* eslint-disable no-restricted-syntax */
2
+ import { describe, expect, it, jest } from "@jest/globals"
3
3
 
4
- const { chunk, unique } = await import("./array.js")
4
+ const { chunk, unique, mutateValues, ascending, descending } = await import("./array.js")
5
5
 
6
6
  describe("chunk", () => {
7
7
  it("splits array into chunks of specified size", () => {
@@ -69,3 +69,121 @@ describe("unique", () => {
69
69
  expect(unique([a, b, a])).toEqual([a, b])
70
70
  })
71
71
  })
72
+
73
+ describe("mutateValues", () => {
74
+ it("mutates values in the object using the callback", () => {
75
+ const obj = { a: 1, b: 2 }
76
+ const result = mutateValues(obj, (v) => v * 2)
77
+ expect(result).toEqual({ a: 2, b: 4 })
78
+ expect(obj).toBe(result) // should mutate in place
79
+ })
80
+
81
+ it("callback receives value, key, and object", () => {
82
+ const obj = { x: 1 }
83
+ const cb = jest.fn((v) => v + 1)
84
+ mutateValues(obj, cb)
85
+ expect(cb).toHaveBeenCalledWith(1, "x", obj)
86
+ })
87
+
88
+ it("returns the same object reference", () => {
89
+ const obj = { foo: "bar" }
90
+ const returned = mutateValues(obj, (v) => v)
91
+ expect(returned).toBe(obj)
92
+ })
93
+
94
+ it("handles empty object", () => {
95
+ const obj = {}
96
+ expect(mutateValues(obj, (v) => v)).toEqual({})
97
+ })
98
+
99
+ it("mutates inherited enumerable properties", () => {
100
+ const proto = { inherited: 1 }
101
+ const obj = Object.create(proto)
102
+ obj.own = 2
103
+ const result = mutateValues(obj, (v) => v + 1)
104
+ expect(result.own).toBe(3)
105
+ expect(result.inherited).toBe(2)
106
+ })
107
+ })
108
+
109
+ describe("ascending", () => {
110
+ it("sorts primitives ascending, undefined/null at end", () => {
111
+ const arr = [undefined, null, 3, 1, 2]
112
+ arr.sort(ascending())
113
+ expect(arr).toEqual([1, 2, 3, null, undefined])
114
+ })
115
+
116
+ it("returns 0 for equal values", () => {
117
+ expect(ascending()(2, 2)).toBe(0)
118
+ expect(ascending()("a", "a")).toBe(0)
119
+ })
120
+
121
+ it("sorts objects by key ascending, undefined/null at end", () => {
122
+ const arr = [{ v: undefined }, { v: 3 }, { v: null }, { v: 1 }, { v: 2 }]
123
+ arr.sort(ascending("v"))
124
+ expect(arr.map((o) => o.v)).toEqual([1, 2, 3, undefined, null])
125
+ })
126
+
127
+ it("returns 0 for equal key values", () => {
128
+ expect(ascending("x")({ x: 5 }, { x: 5 })).toBe(0)
129
+ })
130
+
131
+ it("sorts negative numbers and zero correctly", () => {
132
+ const arr = [0, -2, -1, 2]
133
+ arr.sort(ascending())
134
+ expect(arr).toEqual([-2, -1, 0, 2])
135
+ })
136
+
137
+ it("sorts strings alphabetically", () => {
138
+ const arr = ["b", "a", "c"]
139
+ arr.sort(ascending())
140
+ expect(arr).toEqual(["a", "b", "c"])
141
+ })
142
+
143
+ it("handles objects missing the key", () => {
144
+ const arr = [{ v: 2 }, {}, { v: 1 }]
145
+ arr.sort(ascending("v"))
146
+ expect(arr.map((o) => o.v)).toEqual([1, 2, undefined])
147
+ })
148
+ })
149
+
150
+ describe("descending", () => {
151
+ it("sorts primitives descending, undefined/null at end", () => {
152
+ const arr = [undefined, 1, null, 3, 2]
153
+ arr.sort(descending())
154
+ expect(arr).toEqual([3, 2, 1, null, undefined])
155
+ })
156
+
157
+ it("returns 0 for equal values", () => {
158
+ expect(descending()(2, 2)).toBe(0)
159
+ expect(descending()("a", "a")).toBe(0)
160
+ })
161
+
162
+ it("sorts objects by key descending, undefined/null at end", () => {
163
+ const arr = [{ v: undefined }, { v: 1 }, { v: 3 }, { v: null }, { v: 2 }]
164
+ arr.sort(descending("v"))
165
+ expect(arr.map((o) => o.v)).toEqual([3, 2, 1, undefined, null])
166
+ })
167
+
168
+ it("returns 0 for equal key values", () => {
169
+ expect(descending("x")({ x: 5 }, { x: 5 })).toBe(0)
170
+ })
171
+
172
+ it("sorts negative numbers and zero correctly", () => {
173
+ const arr = [0, -2, -1, 2]
174
+ arr.sort(descending())
175
+ expect(arr).toEqual([2, 0, -1, -2])
176
+ })
177
+
178
+ it("sorts strings reverse alphabetically", () => {
179
+ const arr = ["b", "a", "c"]
180
+ arr.sort(descending())
181
+ expect(arr).toEqual(["c", "b", "a"])
182
+ })
183
+
184
+ it("handles objects missing the key", () => {
185
+ const arr = [{ v: 2 }, {}, { v: 3 }]
186
+ arr.sort(descending("v"))
187
+ expect(arr.map((o) => o.v)).toEqual([3, 2, undefined])
188
+ })
189
+ })
package/src/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./array.js"
2
2
  export * from "./fs.js"
3
+ export * from "./math.js"
3
4
  export * from "./promise.js"
4
5
  export * from "./run.js"
5
6
  export * from "./time.js"
package/src/math.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Module safe for negative numbers i.e. mod(-1, 3) === 2 (not -1 as in -1 % 3).
3
+ * @param {number} n
4
+ * @param {number} m If 0, returns NaN as does n % m.
5
+ * @returns {number}
6
+ */
7
+ export function mod(n, m) {
8
+ return ((n % m) + m) % m
9
+ }
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from "@jest/globals"
2
+ const { mod } = await import("./math.js")
3
+
4
+ describe("mod", () => {
5
+ it("returns n when n is less than m and n is non-negative", () => {
6
+ expect(mod(2, 3)).toBe(2)
7
+ expect(mod(0, 5)).toBe(0)
8
+ })
9
+
10
+ it("wraps negative n into the [0, m) range", () => {
11
+ expect(mod(-1, 3)).toBe(2)
12
+ expect(mod(-4, 3)).toBe(2)
13
+ expect(mod(-2, 5)).toBe(3)
14
+ })
15
+
16
+ it("returns 0 when n is a multiple of m", () => {
17
+ expect(mod(6, 3)).toBe(0)
18
+ expect(mod(-6, 3)).toBe(0)
19
+ })
20
+
21
+ it("handles n greater than m", () => {
22
+ expect(mod(7, 3)).toBe(1)
23
+ expect(mod(14, 5)).toBe(4)
24
+ })
25
+
26
+ it("handles m = 1 (should always return 0)", () => {
27
+ expect(mod(0, 1)).toBe(0)
28
+ expect(mod(5, 1)).toBe(0)
29
+ expect(mod(-3, 1)).toBe(0)
30
+ })
31
+
32
+ it("returns NaN when m is 0", () => {
33
+ expect(mod(5, 0)).toBeNaN()
34
+ expect(mod(0, 0)).toBeNaN()
35
+ expect(mod(-3, 0)).toBeNaN()
36
+ })
37
+ })
package/src/time.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { parseIntSafe } from "./array.js"
2
+ import { mod } from "./math.js"
3
+
1
4
  /**
2
5
  * Gets various ways of representing the current time in EDT. Floors to nearest second by default.
3
6
  * @param {Object} $1
@@ -30,3 +33,70 @@ export function getEasternTime({ days = 0, floorMinute = false } = {}) {
30
33
  const datetime = `${date} ${time}`
31
34
  return { timestamp, date, time, minute, datetime }
32
35
  }
36
+
37
+ /**
38
+ * Checks if the string represents a valid YYYY-MM-DD date.
39
+ * This will return false for dates like "2024-02-31".
40
+ * @param {string} string
41
+ * @returns {boolean}
42
+ */
43
+ export function isDate(string) {
44
+ const match = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/u.exec(string)
45
+ if (!match) {
46
+ return false
47
+ }
48
+ const [, year, month, day] = match.map(Number)
49
+ const date = new Date(`${string}T00:00:00Z`)
50
+ return (
51
+ date.getUTCFullYear() === year &&
52
+ date.getUTCMonth() + 1 === month &&
53
+ date.getUTCDate() === day
54
+ )
55
+ }
56
+
57
+ /**
58
+ * Checks if the string represent a valid HH:mm:ss time.
59
+ * @param {string} string
60
+ * @returns {boolean}
61
+ */
62
+ export function isTime(string) {
63
+ return /^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/u.test(string)
64
+ }
65
+
66
+ /**
67
+ * Checks if a number is a Unix timestamp (i.e. in seconds).
68
+ * Would not validate timestamps set very far into the future.
69
+ * @param {number} ts
70
+ * @param {Object} $1
71
+ * @param {number} $1.max Maximum value for timestamp to allow - default is up to ~2286-11-20; this allows catching ms timestamps
72
+ * @returns {boolean}
73
+ */
74
+ export function isUnixTimestamp(ts, { max = 9999999999 } = {}) {
75
+ return Number.isInteger(ts) && ts >= 0 && ts <= max
76
+ }
77
+
78
+ /**
79
+ * Add an amount of time to a time string.
80
+ * @param {string} timeString HH:mm:ss or HH:mm; parsable numbers separated by :
81
+ * @param {Object} $1
82
+ * @param {number} $1.hours Hours to add to time string
83
+ * @param {number} $1.minutes Minutes to add to time string
84
+ * @returns {string} HH:mm:ss
85
+ */
86
+ export function addTime(timeString, { minutes = 0, hours = 0 }) {
87
+ let [hour, minute, second = 0] = timeString.split(":").map(parseIntSafe)
88
+ hour = mod(hour + hours, 24)
89
+ minute += minutes
90
+ while (minute >= 60) {
91
+ hour = mod(hour + 1, 24)
92
+ minute -= 60
93
+ }
94
+ while (minute < 0) {
95
+ hour = mod(hour - 1, 24)
96
+ minute += 60
97
+ }
98
+ const newTime = [hour, minute, second]
99
+ .map((number) => `${number}`.padStart(2, "0"))
100
+ .join(":")
101
+ return newTime
102
+ }
package/src/time.test.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "@jest/globals"
2
- import { getEasternTime } from "./time.js"
2
+ import { addTime, getEasternTime, isDate, isTime, isUnixTimestamp } from "./time.js"
3
3
 
4
4
  describe("getEasternTime", () => {
5
5
  test("returns correct structure and types", () => {
@@ -46,3 +46,136 @@ describe("getEasternTime", () => {
46
46
  expect(def.datetime).toEqual(explicit.datetime)
47
47
  })
48
48
  })
49
+
50
+ describe("isDate", () => {
51
+ test("returns true for valid YYYY-MM-DD dates", () => {
52
+ expect(isDate("2024-06-01")).toBe(true)
53
+ expect(isDate("1999-12-31")).toBe(true)
54
+ })
55
+
56
+ test("returns false for invalid dates (e.g., 2024-02-31)", () => {
57
+ expect(isDate("2024-02-31")).toBe(false)
58
+ expect(isDate("2023-04-31")).toBe(false)
59
+ })
60
+
61
+ test("returns false for invalid formats", () => {
62
+ expect(isDate("2024/06/01")).toBe(false)
63
+ expect(isDate("06-01-2024")).toBe(false)
64
+ expect(isDate("2024-6-1")).toBe(false)
65
+ expect(isDate("20240601")).toBe(false)
66
+ expect(isDate("abcd-ef-gh")).toBe(false)
67
+ })
68
+
69
+ test("returns false for impossible months and days", () => {
70
+ expect(isDate("2024-00-10")).toBe(false)
71
+ expect(isDate("2024-13-10")).toBe(false)
72
+ expect(isDate("2024-01-00")).toBe(false)
73
+ expect(isDate("2024-01-32")).toBe(false)
74
+ })
75
+
76
+ test("returns true for leap day", () => {
77
+ expect(isDate("2024-02-29")).toBe(true)
78
+ expect(isDate("2023-02-29")).toBe(false)
79
+ })
80
+ })
81
+
82
+ describe("isTime", () => {
83
+ test("returns true for valid HH:mm:ss times", () => {
84
+ expect(isTime("00:00:00")).toBe(true)
85
+ expect(isTime("23:59:59")).toBe(true)
86
+ expect(isTime("12:34:56")).toBe(true)
87
+ })
88
+
89
+ test("returns false for invalid times", () => {
90
+ expect(isTime("24:00:00")).toBe(false)
91
+ expect(isTime("12:60:00")).toBe(false)
92
+ expect(isTime("12:00:60")).toBe(false)
93
+ expect(isTime("1:00:00")).toBe(false)
94
+ expect(isTime("12:0:00")).toBe(false)
95
+ expect(isTime("12:00:0")).toBe(false)
96
+ expect(isTime("12:00")).toBe(false)
97
+ expect(isTime("120000")).toBe(false)
98
+ expect(isTime("ab:cd:ef")).toBe(false)
99
+ })
100
+ })
101
+
102
+ describe("isUnixTimestamp", () => {
103
+ test("returns true for valid unix timestamps in seconds", () => {
104
+ expect(isUnixTimestamp(0)).toBe(true)
105
+ expect(isUnixTimestamp(1700000000)).toBe(true)
106
+ expect(isUnixTimestamp(9999999999)).toBe(true)
107
+ })
108
+
109
+ test("returns false for negative or non-integer or too large values", () => {
110
+ expect(isUnixTimestamp(-1)).toBe(false)
111
+ expect(isUnixTimestamp(1.5)).toBe(false)
112
+ expect(isUnixTimestamp(10000000000)).toBe(false)
113
+ expect(isUnixTimestamp(NaN)).toBe(false)
114
+ expect(isUnixTimestamp(Infinity)).toBe(false)
115
+ })
116
+
117
+ test("respects custom max option", () => {
118
+ expect(isUnixTimestamp(100, { max: 50 })).toBe(false)
119
+ expect(isUnixTimestamp(50, { max: 50 })).toBe(true)
120
+ expect(isUnixTimestamp(51, { max: 50 })).toBe(false)
121
+ })
122
+ })
123
+
124
+ describe("addTime", () => {
125
+ test("adds minutes within the same hour", () => {
126
+ expect(addTime("12:30:00", { minutes: 15 })).toBe("12:45:00")
127
+ expect(addTime("12:30", { minutes: 15 })).toBe("12:45:00")
128
+ })
129
+
130
+ test("adds minutes with hour rollover", () => {
131
+ expect(addTime("12:50:00", { minutes: 15 })).toBe("13:05:00")
132
+ expect(addTime("23:50:00", { minutes: 15 })).toBe("00:05:00")
133
+ })
134
+
135
+ test("subtracts minutes with hour underflow", () => {
136
+ expect(addTime("12:10:00", { minutes: -15 })).toBe("11:55:00")
137
+ expect(addTime("00:10:00", { minutes: -15 })).toBe("23:55:00")
138
+ })
139
+
140
+ test("adds hours with 24-hour rollover", () => {
141
+ expect(addTime("22:15:00", { hours: 3 })).toBe("01:15:00")
142
+ expect(addTime("00:00:00", { hours: 24 })).toBe("00:00:00")
143
+ expect(addTime("23:59:59", { hours: 1 })).toBe("00:59:59")
144
+ })
145
+
146
+ test("subtracts hours with 24-hour underflow", () => {
147
+ expect(addTime("01:15:00", { hours: -3 })).toBe("22:15:00")
148
+ expect(addTime("00:00:00", { hours: -24 })).toBe("00:00:00")
149
+ expect(addTime("00:59:59", { hours: -1 })).toBe("23:59:59")
150
+ })
151
+
152
+ test("handles both hours and minutes together", () => {
153
+ expect(addTime("22:30:00", { hours: 2, minutes: 45 })).toBe("01:15:00")
154
+ expect(addTime("01:15:00", { hours: -2, minutes: -30 })).toBe("22:45:00")
155
+ })
156
+
157
+ test("pads single digit hours, minutes, seconds", () => {
158
+ expect(addTime("1:2:3", { hours: 0, minutes: 0 })).toBe("01:02:03")
159
+ expect(addTime("9:8", { hours: 0, minutes: 0 })).toBe("09:08:00")
160
+ })
161
+
162
+ // Edge case: negative minutes that require multiple hour underflows
163
+ test("handles large negative minutes", () => {
164
+ expect(addTime("05:10:00", { minutes: -130 })).toBe("03:00:00")
165
+ })
166
+
167
+ // Edge case: large positive minutes that require multiple hour rollovers
168
+ test("handles large positive minutes", () => {
169
+ expect(addTime("05:10:00", { minutes: 130 })).toBe("07:20:00")
170
+ })
171
+
172
+ // Edge case: input with seconds omitted
173
+ test("handles input with no seconds", () => {
174
+ expect(addTime("12:34", { minutes: 0 })).toBe("12:34:00")
175
+ })
176
+
177
+ // Edge case: input with all zeros
178
+ test("handles midnight", () => {
179
+ expect(addTime("00:00:00", { hours: 0, minutes: 0 })).toBe("00:00:00")
180
+ })
181
+ })