Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add an ESM version #21

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions esm/index.js
Original file line number Diff line number Diff line change
@@ -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
};
3 changes: 3 additions & 0 deletions esm/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down