aboutsummaryrefslogtreecommitdiff
path: root/client-web/source/helper.ts
blob: 31e500a30fb061b1879edd2173b4707c9c70c255 (plain)
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
/// <reference lib="dom" />

import { parameters } from "./index.ts"

export function get_query_params(): { [key: string]: string } {
    const q: { [key: string]: string } = {}
    for (const kv of window.location.hash.substring(1).split("&")) {
        const [key, value] = kv.split("=")
        q[decodeURIComponent(key)] = decodeURIComponent(value)
    }
    return q
}

export function hex_id(len = 8): string {
    if (len > 8) return hex_id() + hex_id(len - 8)
    return Math.floor(Math.random() * 16 ** len).toString(16).padStart(len, "0")
}

export function parameter_bool(name: string, def: boolean): boolean {
    const v = parameters[name]
    if (!v) return def
    if (v == "0" || v == "false" || v == "no") return false
    if (v == "1" || v == "true" || v == "yes") return true
    alert(`parameter ${name} is invalid`)
    return def
}

export function parameter_number(name: string, def: number): number {
    const v = parameters[name]
    if (!v) return def
    const n = parseFloat(v)
    if (Number.isNaN(n)) {
        alert(`parameter ${name} is invalid`)
        return def
    }
    return n
}

export function parameter_string(name: string, def: string): string {
    const v = parameters[name]
    if (!v) return def
    return v
}