Skip to content

Commit 219b6ab

Browse files
committed
add Generating a Unique ID recipe
1 parent 017b657 commit 219b6ab

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
layout: recipe
3+
title: Generating a Unique ID
4+
chapter: Strings
5+
---
6+
## Problem
7+
8+
You want to generate a random unique identifier.
9+
10+
## Solution
11+
12+
You can create a Base 36 encoded string from a random number.
13+
14+
{% highlight coffeescript %}
15+
uniqueId = (length=8) ->
16+
id = ""
17+
id += Math.random().toString(36).substr(2) while id.length < length
18+
id.substr 0, length
19+
20+
uniqueId() # => n5yjla3b
21+
uniqueId(2) # => 0d
22+
uniqueId(20) # => ox9eo7rt3ej0pb9kqlke
23+
uniqueId(40) # => xu2vo4xjn4g0t3xr74zmndshrqlivn291d584alj
24+
{% endhighlight %}
25+
26+
## Discussion
27+
28+
There are other possible techniques, but this is relatively performant and flexible.

0 commit comments

Comments
 (0)