Last active
January 27, 2023 17:00
-
-
Save dingosky/86328fc8b51d6b3037087ab1a8d14b4f to your computer and use it in GitHub Desktop.
Common random ID strategy
This file contains 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
# 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" |
This file contains 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
# 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' |
This file contains 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
// 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' |
This file contains 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
// 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