Skip to content

Instantly share code, notes, and snippets.

@dingosky
Last active January 27, 2023 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dingosky/86328fc8b51d6b3037087ab1a8d14b4f to your computer and use it in GitHub Desktop.
Save dingosky/86328fc8b51d6b3037087ab1a8d14b4f to your computer and use it in GitHub Desktop.
Common random ID strategy
# Elixir
iex> chars = Enum.to_list(?a..?z)
iex> k = length(chars)
iex> common_id = fn n -> for(_ <- 1..n, do: :rand.uniform(k) - 1)
|> Enum.map(&(chars |> Enum.at(&1)))
|> List.to_string()
end
iex> common_id.(8)
# => "qyyrpoco"
# Python
from random import randint
import string
chars = string.ascii_lowercase
n_chars = len(chars)
common_id = lambda len: "".join([chars[randint(0,n_chars)] for _ in range(len)])
common_id(8)
# => 'vbautjwb'
// JavaScript
const commonId = (n) => {
const chars = 'abcdefghijklmnopqrstuvwxyz'
let id = '';
for (let i = 0; i < n; i++) {
id += chars.charAt(Math.floor(Math.random() * chars.length));
}
return id
}
commonId(8)
// => 'btvjyxfe'
// Swift
let chars = (UInt8(ascii: "a")...UInt8(ascii: "z")).map { $0 }
func commonId(len: Int) -> String {
String(bytes: (0..<len)
.map { $0 }
.map { _ in
chars[Int.random(in: 0..<chars.count)]
}, encoding: .ascii)!
}
commonId(len: 8)
// => "poqeumsd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment