diff --git a/esm/index.js b/esm/index.js new file mode 100644 index 0000000..3b76d02 --- /dev/null +++ b/esm/index.js @@ -0,0 +1,70 @@ +'use strict'; + +var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') + , length = 64 + , map = {} + , seed = 0 + , i = 0 + , prev; + +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +function encode(num) { + var encoded = ''; + + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + + return encoded; +} + +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +function decode(str) { + var decoded = 0; + + for (i = 0; i < str.length; i++) { + decoded = decoded * length + map[str.charAt(i)]; + } + + return decoded; +} + +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +function yeast() { + var now = encode(+new Date()); + + if (now !== prev) return seed = 0, prev = now; + return now +'.'+ encode(seed++); +} + +// +// Map each character to its index. +// +for (; i < length; i++) map[alphabet[i]] = i; + +// +// Expose the `yeast`, `encode` and `decode` functions. +// +export { + encode, + decode, + yeast as default +}; diff --git a/esm/package.json b/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/package.json b/package.json index e17cb1e..d4d927d 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,11 @@ "version": "0.1.2", "description": "Tiny but linear growing unique id generator", "main": "index.js", + "module": "./esm/index.js", + "exports": { + "import": "./esm/index.js", + "require": "index.js" + }, "scripts": { "100%": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100", "test-node": "istanbul cover _mocha --report lcovonly -- test.js",