Viewing File: /usr/local/cpanel/share/libraries/cjt2/src/util/unique.js

/*
# cjt/util/unique.js                              Copyright(c) 2020 cPanel, L.L.C.
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
*/

/* global define: false */

define(
    function() {

        /**
         * Generate unique IDs for use as pseudo-private/protected names.
         * Similar in concept to
         * <http: *wiki.ecmascript.org/doku.php?id=strawman:names>.
         *
         * The goals of this function are twofold:
         *
         * * Provide a way to generate a string guaranteed to be unique when compared
         * to other strings generated by this function.
         * * Make the string complex enough that it is highly unlikely to be
         * accidentally duplicated by hand (this is key if you're using `ID`
         * as a private/protected name on an object).
         *
         * @param  {String} [prefix] Optional prefix to add to the id.
         * @return {String}          Unique id based on random number generation.
         * @example
         *
         * With default options:
         *
         * var privateName = unique();
         * var o = {};
         * o[privateName] = "bar";
         *
         * privateName will be something like: '_???????'
         *
         * With a prefix:
         *
         * var privateName = unique("cp");
         * var o = {};
         * o[privateName] = "bar";
         *
         * privateName will be something like: 'cp_???????'
         */
        return function(prefix) {

            // Math.random should be unique because of its seeding algorithm.
            // Convert it to base 36 (numbers + letters), and grab the first 9 characters
            // after the decimal.
            return prefix + "_" + Math.random().toString().substr(2, 9);
        };
    }
);
Back to Directory File Manager