Skip to content

Instantly share code, notes, and snippets.

@itolosa
Created March 12, 2018 14:34
Show Gist options
  • Save itolosa/a1dc4fc50d90160b45c59673d9810369 to your computer and use it in GitHub Desktop.
Save itolosa/a1dc4fc50d90160b45c59673d9810369 to your computer and use it in GitHub Desktop.
Porting of yeast.js to yeast.py
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