summaryrefslogtreecommitdiff
path: root/src/lib/random.source.sh
blob: ca5c7d3c36b69934a0c8c3a48c41debc81abd685 (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
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
random_seed_is_set() {
    [ -n "$RANDOM_SEED" ]
}

deterministic_index() {
    local -r namespace="$1"; shift
    local -r count="$1"; shift
    local checksum

    checksum=$(printf '%s' "${RANDOM_SEED}:$namespace" | cksum)
    checksum=${checksum%% *}

    printf '%s\n' $(( checksum % count ))
}

random_index() {
    local -r namespace="$1"; shift
    local -r count="$1"; shift

    if random_seed_is_set; then
        deterministic_index "$namespace" "$count"
    else
        printf '%s\n' $(( RANDOM % count ))
    fi
}

random_animation_css_class() {
    local -r speed="$1"; shift
    local -r context="${1:-$speed}"
    local -i index
    local -a classes=(
        "animate-opacity-$speed"
        "animate-top-$speed"
        "animate-left-$speed"
        "animate-right-$speed"
        "animate-bottom-$speed"
        "animate-zoom-$speed"
        "animate-snap-rotate-$speed"
        "animate-hard-zoom-$speed"
        "animate-slam-left-$speed"
        "animate-slam-right-$speed"
        "animate-flash-in-$speed"
        "animate-invert-pop-$speed"
        "animate-posterize-pop-$speed"
        "animate-skew-snap-$speed"
        "animate-glitch-step-$speed"
    )

    index=$(random_index "animation:$speed:$context" "${#classes[@]}")
    printf '%s\n' "${classes[index]}"
}

deterministic_shuffle() {
    local checksum
    local line

    while IFS= read -r line; do
        checksum=$(printf '%s' "${RANDOM_SEED}:shuffle:$line" | cksum)
        checksum=${checksum%% *}
        printf '%010u\t%s\n' "$checksum" "$line"
    done | sort -n -k1,1 -k2,2 | cut -f2-
}

maybe_shuffle() {
    if [ "$SHUFFLE" = yes ]; then
        if random_seed_is_set; then
            deterministic_shuffle
        else
            # $SORT (compat.source.sh): -R (random shuffle) is GNU-only.
            "$SORT" -R
        fi
    else
        # Plain sort here is POSIX-portable; no GNU-only flag involved.
        sort
    fi
}