util_misc_util.js

/**
 * @module Util
 * @fileoverview Contains Util class.
 */

import Sprite from "../../registry/sprite/sprite.js";

/**
 * @class
 * Contains static functions for utility purposes.
 */
class Util {
    /**
     * Linearly interpolate between two values.
     * @param {number} a First value
     * @param {number} b Seconds value
     * @param {number} alpha Progress (0 - 1)
     * @returns {number} Number at specified point
     */
    static lerp(a, b, alpha) {
        return (b - a) * alpha + a;
    }

    /**
     * Smoothly linearly interpolate between two values.
     * @param {number} a First value
     * @param {number} b Seconds value
     * @param {number} alpha Progress (0 - 1)
     * @returns {number} Number at specified point
     */
    static smoothLerp(a, b, alpha) {
        alpha = alpha * alpha * (3 - 2 * alpha);
        return this.lerp(a, b, alpha);
    }

    /**
     * Get a random element from an array.
     * @param {any[]} array Array to choose from
     * @returns {any} Randomly selected element
     */
    static randomChoice(array) {
        return array[Math.floor(Math.random() * array.length)];
    }

    /**
     * Convert a single value denoting seconds to HH:MM:SS format.
     * @param {number} num Seconds
     * @returns {string} Formatted string
     */
    static timeFormat(num) {
        const h = Math.floor(num / 3600);
        num %= 3600;
        const m = Math.floor(num / 60);
        num %= 60;

        const fm = m.toString().padStart(2, '0');
        const fs = num.toFixed(0).padStart(2, '0');

        let string = "";
        if (h > 0)
            string = `${h}:${fm}:${fs}`;
        else
            string = `${fm}:${fs}`;

        return string;
    }

    static loadImage(path, onload = image => {}) {
        fetch(path)
            .then(res => res.blob())
            .then(blob => {
                const reader = new FileReader();
                reader.onloadend = () => {
                    const url = URL.createObjectURL(blob);
                    const image = new Image();
                    image.src = url;

                    image.onload = () => {
                        //URL.revokeObjectURL(url);
                        onload(image);
                    }
                };

                reader.readAsDataURL(blob);
            });
    }
}

export default Util;