We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 017b657 commit 219b6abCopy full SHA for 219b6ab
chapters/strings/generating-a-unique-id.md
@@ -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