Created
March 12, 2018 14:34
-
-
Save itolosa/a1dc4fc50d90160b45c59673d9810369 to your computer and use it in GitHub Desktop.
Porting of yeast.js to yeast.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_' | |
length = 64 | |
map_h = {} | |
seed = 0 | |
i = 0 | |
prev = None | |
import math | |
# | |
# Return a string representing the specified number. | |
# | |
# @param {Number} num The number to convert. | |
# @returns {String} The string representation of the number. | |
# @api public | |
# | |
def encode(num): | |
encoded = '' | |
while True: | |
encoded = alphabet[num % length] + encoded | |
num = math.floor(float(num) / float(length)) | |
if not (num > 0): | |
break | |
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 | |
# | |
def decode(str): | |
decoded = 0 | |
for i in range(len(str)): | |
decoded = decoded * length + map_h[str[i]]; | |
return decoded | |
# | |
# Yeast: A tiny growing id generator. | |
# | |
# @returns {String} A unique id. | |
# @api public | |
# | |
def yeast(): | |
global prev, seed | |
now = encode(int(time.time() * 1000)) | |
r = str(now) +'.'+ str(encode(seed)) | |
seed += 1 | |
return r | |
# | |
# Map each character to its index. | |
# | |
for i in range(length): | |
map_h[alphabet[i]] = i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment