-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
463 lines (406 loc) · 16.8 KB
/
main.js
File metadata and controls
463 lines (406 loc) · 16.8 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// Browser UI for the UnSure calculator, reusing the shared core in calc-core.js
(function () {
const calcCoreLib = window.UnsureCalcCore;
if (!calcCoreLib) {
throw new Error("calc-core.js not loaded; ensure script order in index.html");
}
const {
tokenize,
shuntingYard,
evalRpn,
evaluateExpression,
evaluateExpressionWithSteps,
getQuantiles,
formatNumber,
generateTextHistogram
} = calcCoreLib;
const FX_CACHE_KEY = "unsureCalcFx.v1";
const BIG_25_CURRENCIES = [
"USD", "GBP", "JPY", "CHF", "CAD", "AUD", "NZD", "SEK", "NOK", "DKK",
"PLN", "CZK", "HUF", "RON", "TRY", "CNY", "HKD", "SGD", "KRW", "INR",
"MXN", "BRL", "ZAR", "AED"
];
const FX_SYMBOLS_QUERY = BIG_25_CURRENCIES.join(",");
const FX_ENDPOINTS = [
`https://api.frankfurter.dev/v1/latest?base=EUR&symbols=${FX_SYMBOLS_QUERY}`,
`https://api.frankfurter.app/latest?base=EUR&symbols=${FX_SYMBOLS_QUERY}`,
];
const FALLBACK_BASE_RATES = { PLN: 4.22 };
let fxLoadPromise = null;
let fxState = null;
function escapeHtml(raw) {
if (raw === null || raw === undefined) return "";
return String(raw)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function renderStepsHtml(steps) {
if (!Array.isArray(steps) || steps.length === 0) return "";
return steps
.map((line, index) => `<div>${index}. ${escapeHtml(line)}</div>`)
.join("");
}
function getExpressionFromQuery() {
const query = window.location.search.startsWith("?")
? window.location.search.slice(1)
: window.location.search;
if (!query) return "";
const pair = query
.split("&")
.map((chunk) => chunk.split("="))
.find(([key]) => key && decodeURIComponent(key) === "expr");
if (!pair || pair.length < 2) return "";
const rawValue = pair.slice(1).join("=");
try {
return decodeURIComponent(rawValue);
} catch (e) {
console.error("Failed to decode expr query parameter", e);
return rawValue;
}
}
function getLocalDateStamp(date = new Date()) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
function readCachedFxData() {
try {
const raw = window.localStorage.getItem(FX_CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object") return null;
if (typeof parsed.day !== "string" || parsed.day.length < 8) return null;
const normalizedRates = normalizeBaseRates(parsed.rates);
if (Object.keys(normalizedRates).length === 0) return null;
return {
day: parsed.day,
rateDate: typeof parsed.rateDate === "string" ? parsed.rateDate : parsed.day,
rates: normalizedRates,
fetchedAt: typeof parsed.fetchedAt === "string" ? parsed.fetchedAt : null,
};
} catch (error) {
console.warn("Unable to read cached FX data", error);
return null;
}
}
function writeCachedFxData(data) {
try {
window.localStorage.setItem(FX_CACHE_KEY, JSON.stringify(data));
} catch (error) {
console.warn("Unable to cache FX data", error);
}
}
function normalizeBaseRates(rawRates) {
const normalized = {};
if (!rawRates || typeof rawRates !== "object") return normalized;
for (const code of BIG_25_CURRENCIES) {
const rate = rawRates[code] ?? rawRates[code.toLowerCase()];
if (typeof rate === "number" && isFinite(rate) && rate > 0) {
normalized[code] = rate;
}
}
for (const [code, rate] of Object.entries(FALLBACK_BASE_RATES)) {
if (!(code in normalized)) {
normalized[code] = rate;
}
}
return normalized;
}
function buildFxRequestUrl(endpoint, forceRefresh) {
if (!forceRefresh) return endpoint;
const separator = endpoint.includes("?") ? "&" : "?";
return `${endpoint}${separator}t=${Date.now()}`;
}
async function fetchLiveFxRates(today, forceRefresh = false) {
let lastError = null;
for (const endpoint of FX_ENDPOINTS) {
try {
const response = await fetch(buildFxRequestUrl(endpoint, forceRefresh), {
cache: forceRefresh ? "reload" : "no-store",
});
if (!response.ok) {
throw new Error(`${endpoint} HTTP ${response.status}`);
}
const payload = await response.json();
const normalizedRates = normalizeBaseRates(payload?.rates);
if (Object.keys(normalizedRates).length === 0) {
throw new Error(`${endpoint} invalid FX payload`);
}
const rateDate = typeof payload?.date === "string" ? payload.date : today;
return { source: "live", rates: normalizedRates, day: today, rateDate };
} catch (error) {
lastError = error;
}
}
throw lastError || new Error("All FX endpoints failed");
}
function buildCurrencyRateOptions(baseRates) {
const lowerRates = {};
for (const [code, rate] of Object.entries(baseRates || {})) {
if (typeof rate !== "number" || !isFinite(rate) || rate <= 0) continue;
lowerRates[code.toLowerCase()] = rate;
}
return {
currencyRates: {
eur: lowerRates
}
};
}
function isCurrencyLikeExpression(expression) {
return /[a-z]/i.test(expression);
}
function renderRateStatus(rateStatusDisplay, state, options = {}) {
if (!rateStatusDisplay || !state) return;
const onRefetch = typeof options.onRefetch === "function" ? options.onRefetch : null;
const eurPln = state.rates?.PLN;
const pairText = typeof eurPln === "number" ? `EUR/PLN ${eurPln.toFixed(4)}.` : "";
const currencyCount = 1 + Object.keys(state.rates || {}).length;
if (state.source === "live") {
rateStatusDisplay.textContent = `Top ${currencyCount} currencies from Frankfurter (${state.rateDate}).`;
return;
}
if (state.source === "cached") {
rateStatusDisplay.textContent = `Top ${currencyCount} currencies cached ${state.rateDate}.`;
if (onRefetch) {
const refetchLink = document.createElement("a");
refetchLink.href = "#";
refetchLink.textContent = "Refetch";
refetchLink.className = "underline cursor-pointer";
refetchLink.addEventListener("click", (event) => {
event.preventDefault();
onRefetch();
});
rateStatusDisplay.appendChild(document.createTextNode(" "));
rateStatusDisplay.appendChild(refetchLink);
}
return;
}
rateStatusDisplay.textContent = `${pairText} Live rates unavailable, using fallback snapshot.`;
}
async function loadDailyFxRateState(options = {}) {
const forceRefresh = options.forceRefresh === true;
const today = getLocalDateStamp();
if (!forceRefresh && fxState && fxState.day === today) return fxState;
if (fxLoadPromise && !forceRefresh) return fxLoadPromise;
if (fxLoadPromise && forceRefresh) {
try {
await fxLoadPromise;
} catch (_error) {
// Ignore prior in-flight failure and force a new fetch below.
}
}
fxLoadPromise = (async () => {
const cached = readCachedFxData();
if (!forceRefresh && cached && cached.day === today) {
fxState = {
source: "cached",
rates: cached.rates,
day: cached.day,
rateDate: cached.rateDate || cached.day,
};
return fxState;
}
try {
const liveState = await fetchLiveFxRates(today, forceRefresh);
const toCache = {
rates: liveState.rates,
day: today,
rateDate: liveState.rateDate,
fetchedAt: new Date().toISOString(),
};
writeCachedFxData(toCache);
fxState = liveState;
return fxState;
} catch (error) {
if (cached) {
fxState = {
source: "cached",
rates: cached.rates,
day: cached.day,
rateDate: cached.rateDate || cached.day,
};
return fxState;
}
fxState = {
source: "fallback",
rates: normalizeBaseRates(FALLBACK_BASE_RATES),
day: today,
rateDate: today,
error: error?.message || "Unknown error",
};
return fxState;
} finally {
fxLoadPromise = null;
}
})();
return fxLoadPromise;
}
function setupBrowserHandlers() {
const expressionInput = document.getElementById("expression");
const calculateBtn = document.getElementById("calculateBtn");
const resultSummaryDisplay = document.getElementById("result-summary");
const resultHistogramDisplay = document.getElementById("result-histogram");
const resultContainer = document.getElementById("result-container");
const rateStatusDisplay = document.getElementById("rate-status");
if (!expressionInput || !calculateBtn || !resultSummaryDisplay || !resultHistogramDisplay || !resultContainer) {
return;
}
const expr = getExpressionFromQuery();
if (expr && expr !== "null") {
expressionInput.value = expr;
}
function reset() {
expressionInput.value = "";
calculate();
expressionInput.focus();
}
function renderRateStatusWithRefetch(state) {
renderRateStatus(rateStatusDisplay, state, {
onRefetch: handleRefetchRates,
});
}
async function handleRefetchRates() {
if (!rateStatusDisplay) return;
rateStatusDisplay.textContent = "Refetching daily FX rates...";
const state = await loadDailyFxRateState({ forceRefresh: true });
renderRateStatusWithRefetch(state);
if (isCurrencyLikeExpression(expressionInput.value || "")) {
calculate();
}
}
async function calculate() {
const expression = expressionInput.value;
resultSummaryDisplay.innerHTML = "<div>Calculating...</div>";
resultHistogramDisplay.innerHTML = "";
resultContainer.style.visibility = "hidden";
resultContainer.classList.remove("hidden");
resultContainer.classList.remove("border-red-600");
resultSummaryDisplay.classList.remove("text-red-600");
if (expression) {
const params = new URLSearchParams(window.location.search);
params.delete("expr");
const encodedExpression = encodeURIComponent(expression);
const rest = params.toString();
const query = rest ? `?${rest}&expr=${encodedExpression}` : `?expr=${encodedExpression}`;
window.history.pushState(null, "", query);
}
setTimeout(async () => {
try {
if (!expression.trim()) {
resultSummaryDisplay.innerHTML = "Enter an expression to calculate.";
resultHistogramDisplay.innerHTML = "";
resultContainer.style.visibility = "visible";
return;
}
let evaluationOptions = {};
if (isCurrencyLikeExpression(expression)) {
const state = await loadDailyFxRateState();
renderRateStatusWithRefetch(state);
evaluationOptions = buildCurrencyRateOptions(state.rates);
}
const evaluation = evaluateExpressionWithSteps(expression, undefined, evaluationOptions);
const result = evaluation?.result;
if (!result) {
resultSummaryDisplay.innerHTML = "";
resultContainer.style.visibility = "visible";
return;
}
let summaryHtml = "";
let hasError = false;
if (evaluation.isCurrencyExpression) {
const displayValue = result.display ??
`${formatNumber(result.mean)}${evaluation.currency ? evaluation.currency : ""}`;
const currencySuffix = evaluation.currency ? evaluation.currency : "";
if (isNaN(result.mean)) {
summaryHtml += `<div><span class="text-red-600">Currency Result Contains NaN</span></div>`;
hasError = true;
} else {
summaryHtml += `<div>Final Result: ${escapeHtml(displayValue)}</div>`;
}
const stepsHtml = renderStepsHtml(evaluation.steps);
if (stepsHtml) {
summaryHtml += `<div class="mt-2">Steps:</div>`;
summaryHtml += `<div class="mt-1 text-sm">${stepsHtml}</div>`;
}
if (result.samples) {
const quantiles = getQuantiles(result.samples);
if (isNaN(quantiles.p05) || isNaN(quantiles.p95)) {
summaryHtml += `<div><span class="text-red-600">Simulated Result Contains NaN/Infinity</span></div>`;
hasError = true;
} else {
summaryHtml += `<div>Simulated Range (5%-95%): ${formatNumber(quantiles.p05)}${currencySuffix} ~ ${formatNumber(quantiles.p95)}${currencySuffix}</div>`;
}
const histogramLines = generateTextHistogram(result.samples);
resultHistogramDisplay.innerHTML = histogramLines.join("<br>");
} else {
resultHistogramDisplay.innerHTML = "";
}
} else {
if (isNaN(result.mean) || isNaN(result.min) || isNaN(result.max)) {
summaryHtml += `<div><span class="text-red-600">Exact Result Contains NaN</span></div>`;
hasError = true;
} else {
summaryHtml += `<div>Exact Average: ${formatNumber(result.mean)}</div>`;
summaryHtml += `<div>Exact Range : ${formatNumber(result.min)} - ${formatNumber(result.max)}</div>`;
}
if (result.samples) {
const quantiles = getQuantiles(result.samples);
if (isNaN(quantiles.p05) || isNaN(quantiles.p95)) {
summaryHtml += `<div><span class="text-red-600">Simulated Result Contains NaN/Infinity</span></div>`;
hasError = true;
} else {
summaryHtml += `<div>Simulated Range (5%-95%): ${formatNumber(quantiles.p05)} ~ ${formatNumber(quantiles.p95)}</div>`;
}
const histogramLines = generateTextHistogram(result.samples);
resultHistogramDisplay.innerHTML = histogramLines.join("<br>");
} else {
resultHistogramDisplay.innerHTML = "";
summaryHtml += `<div class="mt-2">Result is an exact number, no distribution to simulate</div>`;
}
}
resultSummaryDisplay.innerHTML = summaryHtml;
if (hasError) {
resultContainer.classList.add("border-red-600");
}
} catch (error) {
console.error("Calculation Error:", error);
resultSummaryDisplay.innerHTML = `<div><span class="text-red-600">Error: ${error.message}</span></div>`;
resultContainer.classList.add("border-red-600");
resultHistogramDisplay.innerHTML = "";
}
resultContainer.style.visibility = "visible";
}, 10);
}
calculateBtn.addEventListener("click", calculate);
expressionInput.addEventListener("keypress", (event) => {
if (event.key === "Enter") calculate();
});
document.querySelector('h1')?.addEventListener('click', reset);
if (!expressionInput.value) {
expressionInput.value = "7~10 * 17~23";
}
loadDailyFxRateState()
.then((state) => renderRateStatusWithRefetch(state))
.catch(() => renderRateStatusWithRefetch({
source: "fallback",
rates: normalizeBaseRates(FALLBACK_BASE_RATES),
rateDate: getLocalDateStamp(),
}));
calculate();
// Export to window for manual debugging
window.unsureCalc = {
tokenize,
shuntingYard,
evalRpn,
evaluateExpression,
reset,
calculate,
};
}
// Run in browser
document.addEventListener("DOMContentLoaded", () => {
setupBrowserHandlers();
});
})();