feat: implement basic js utilities
parent
f1897f581e
commit
3abc6a2779
@ -0,0 +1,61 @@
|
||||
import Big from "big.js";
|
||||
import { fromUnixTime, intlFormat } from "date-fns";
|
||||
|
||||
export const sleep = (timeout: number) =>
|
||||
new Promise((res) => setTimeout(res, timeout));
|
||||
|
||||
export const parseOptionalFloat = (text: string) => {
|
||||
const result = parseFloat(text);
|
||||
if (Number.isNaN(result)) return undefined;
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// Source: https://stackoverflow.com/a/34591063
|
||||
export const roundToStep = (value: number, step = 1.0) => {
|
||||
const inv = new Big(1.0).div(step);
|
||||
return inv.mul(value).round().div(inv).toNumber();
|
||||
};
|
||||
|
||||
export const getDisplayDateFromUnix = function (unix: number) {
|
||||
return intlFormat(
|
||||
fromUnixTime(unix),
|
||||
{
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
},
|
||||
{
|
||||
locale: "de-CH",
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
export const resetInput =
|
||||
(defaultValue: any, eventName = "input") =>
|
||||
(evt: FocusEvent) => {
|
||||
const el = evt.target as HTMLInputElement | null;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (el.value !== "") {
|
||||
return;
|
||||
}
|
||||
|
||||
el.value = defaultValue;
|
||||
const event = new Event(eventName, { bubbles: true });
|
||||
el.dispatchEvent(event);
|
||||
};
|
||||
|
||||
// https://dev.to/codebubb/how-to-shuffle-an-array-in-javascript-2ikj
|
||||
export const shuffle = (list: any[]) => {
|
||||
for (let i = list.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
const temp = list[i];
|
||||
list[i] = list[j];
|
||||
list[j] = temp;
|
||||
}
|
||||
|
||||
return list;
|
||||
};
|
Loading…
Reference in New Issue