types/randomid.js

'use strict';

/**
 * @author schukai GmbH
 */

import {Monster, ID} from "./id.js";
import {getGlobal} from "./global.js";
import {random} from "../math/random.js";

/**
 * @private
 * @type {number}
 */
let internalCounter = 0;

/**
 * you can call the method via the monster namespace `new Monster.Types.RandomID()`.
 *
 * ```
 * <script type="module">
 * import {Monster} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.6.0/dist/modules/types/randomid.js';
 * console.log(new Monster.Types.RandomID())
 * </script>
 * ```
 *
 * Alternatively, you can also integrate this function individually.
 *
 * ```
 * <script type="module">
 * import {ID} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.6.0/dist/modules/types/randomid.js';
 * console.log(new RandomID())
 * </script>
 * ```
 *
 * @since 1.6.0
 * @copyright schukai GmbH
 * @memberOf Monster/Types
 */
class RandomID extends ID {

    /**
     * create new object
     */
    constructor() {
        super();

        internalCounter += 1;

        this.id = getGlobal().btoa(random(1, 10000))
            .replace(/=/g, '')
            /** No numbers at the beginning of the ID, because of possible problems with DOM */
            .replace(/^[0-9]+/, 'X') + internalCounter;
    }

}

Monster.assignToNamespace('Monster.Types', RandomID);
export {Monster, RandomID}