types/id.js

'use strict';

/**
 * @author schukai GmbH
 */

import {Monster, Base} from './base.js';
import {validateString} from "./validate.js";

/**
 * @private
 * @type {Map<string, integer>}
 */
let internalCounter = new Map;

/**
 * with the id class, sequences of ids can be created. for this purpose, an internal counter is incremented for each prefix.
 * thus, the first id with the prefix `myid` will be `myid1` and the second id `myid2`.
 * The ids are the same for every call, for example on a web page.
 *
 * so the ids can also be used for navigation. you just have to take care that the order stays the same.
 *
 * you can call the method via the monster namespace `new Monster.Types.ID()`.
 *
 * ```
 * <script type="module">
 * import {Monster} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.6.0/dist/modules/types/id.js';
 * console.log(new Monster.Types.ID())
 * </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/id.js';
 * console.log(new ID())
 * </script>
 * ```
 *
 * as of version 1.6.0 there is the new RandomID. this ID class is continuous from now on.
 *
 * @since 1.0.0
 * @copyright schukai GmbH
 * @memberOf Monster/Types
 */
class ID extends Base {

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

        if (prefix === undefined) {
            prefix = "id";
        }

        validateString(prefix);

        if (!internalCounter.has(prefix)) {
            internalCounter.set(prefix, 1);
        }

        let count = internalCounter.get(prefix);
        this.id = prefix + count;

        internalCounter.set(prefix, ++count);
    }

    /**
     * @return {string}
     */
    toString() {
        return this.id;
    }

}

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