-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.mjs
More file actions
201 lines (156 loc) · 5.63 KB
/
utils.mjs
File metadata and controls
201 lines (156 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
function bufferToHexString(buffer) {
return Array.from(new Uint8Array(buffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
export function degreesToCompass8(degrees) {
const directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
const index = Math.round(degrees / 45) % 8;
return directions[index];
}
export function normalizeText(text) {
return text.normalize('NFD').trim().replaceAll(/[\n\u0300-\u036f]/g, '')
}
export function calculateHeadingAndDistance(myLat, myLon, targetLat, targetLon) {
const R = 6371;
const toRadians = (degrees) => degrees * (Math.PI / 180);
const toDegrees = (radians) => radians * (180 / Math.PI);
const lat1Rad = toRadians(myLat);
const lon1Rad = toRadians(myLon);
const lat2Rad = toRadians(targetLat);
const lon2Rad = toRadians(targetLon);
const dLat = lat2Rad - lat1Rad;
const dLon = lon2Rad - lon1Rad;
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const y = Math.sin(dLon) * Math.cos(lat2Rad);
const x =
Math.cos(lat1Rad) * Math.sin(lat2Rad) -
Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(dLon);
const bearingRad = Math.atan2(y, x);
const heading = (toDegrees(bearingRad) + 360) % 360;
return {
heading: degreesToCompass8(heading),
distance: R * c
};
}
// https://nominatim.org/release-docs/develop/api/Reverse/
export function geoCode(lat, lon) {
const url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}`;
return fetch(url)
.then(res => {
if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
return res.json();
})
.then(json => {
if (json.error) return '';
const address = json.address || {};
let location = '';
if (address.village) location += `${address.village}, `;
else if (address.town) location += `${address.town}, `;
else if (address.city) location += `${address.city}, `;
if (address.municipality) location += `${address.municipality}, `;
if (address.state) location += `${address.state}, `;
if (address.country) location += `${address.country}`;
return location.replace(/,\s*$/, '');
})
.catch(err => {
console.error('Geocoding failed:', err);
return '';
});
}
export function trimAndNormalize(str) {
return normalizeText(str.replaceAll(/[\n\s]+/g, ' ').trim())
}
export function shortenToBytes(str, maxBytes) {
if (typeof str !== 'string' || typeof maxBytes !== 'number' || maxBytes < 0) {
return '';
}
const encoder = new TextEncoder();
const encoded = encoder.encode(str);
if (encoded.length <= maxBytes) {
return str;
}
const decoder = new TextDecoder('utf-8');
const truncatedBytes = encoded.slice(0, maxBytes);
let truncatedString = decoder.decode(truncatedBytes, { stream: true });
while (encoder.encode(truncatedString).length > maxBytes) {
truncatedString = truncatedString.slice(0, -1);
}
const match = truncatedString.match(/^(.*)\s/s);
if (match && match[1]) {
return match[1];
} else {
return '';
}
}
export function splitStringToByteChunks(str, maxBytes) {
if (typeof str !== 'string' || typeof maxBytes !== 'number' || maxBytes <= 0) {
return [];
}
const encoder = new TextEncoder();
const decoder = new TextDecoder('utf-8', { fatal: false }); // non-fatal for easy decoding
const chunks = [];
let remainingStr = str.trim();
while (remainingStr.length > 0) {
if (encoder.encode(remainingStr).length <= maxBytes) {
chunks.push(remainingStr);
break;
}
let candidateChunk = '';
const encoded = encoder.encode(remainingStr);
const truncatedBytes = encoded.slice(0, maxBytes);
candidateChunk = decoder.decode(truncatedBytes, { stream: true });
while (encoder.encode(candidateChunk).length > maxBytes) {
candidateChunk = candidateChunk.slice(0, -1);
}
if (candidateChunk.length === 0) {
const oneCharLessBytes = encoded.slice(0, maxBytes - 3); // Assume max 3 bytes for a char
candidateChunk = decoder.decode(oneCharLessBytes, { stream: true });
if (candidateChunk.length === 0) break; // Safety break
}
let splitIndex = -1;
const sentenceMatch = candidateChunk.match(/^(.*[.?!])\s/s);
if (sentenceMatch && sentenceMatch[1]) {
splitIndex = sentenceMatch[1].length;
} else {
const whitespaceMatch = candidateChunk.match(/^(.*)\s/s);
if (whitespaceMatch && whitespaceMatch[1]) {
splitIndex = whitespaceMatch[1].length;
}
}
let finalChunk;
if (splitIndex > 0) {
finalChunk = remainingStr.substring(0, splitIndex);
} else {
finalChunk = candidateChunk;
}
chunks.push(finalChunk.trim());
remainingStr = remainingStr.substring(finalChunk.length).trim();
}
return chunks;
}
export function sleep(milis) {
return new Promise(resolve => setTimeout(resolve, milis));
}
export async function shaSumHex(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await globalThis.crypto.subtle.digest('SHA-1', data);
return bufferToHexString(hash);
}
export function setAlarm(time, callback) {
const [hours, minutes] = time.split(':');
const seenAlarms = {};
setInterval(() => {
const date = new Date();
const currentDate = date.toISOString().split('T')[0];
if (!(date.getHours() == hours && date.getMinutes() == minutes && !seenAlarms[currentDate])) return;
console.debug('alarm triggered', date);
seenAlarms[currentDate] = 1;
callback(date);
}, 30 * 1000);
}