shortId creates amazingly short non-sequential url-friendly unique IDs. Perfect for url shorteners, MongoDB and Redis as well as any other ID users might see.
1
|
npm install shortId |
Features
- By default 7-12 url-friendly characters:
A-Z
,a-z
,0-9
,_-
- Non-sequential so they are not predictable
- Supports cluster (automatically), custom seeds, custom alphabet
Example
1
2
3
4
|
var shortId = require( 'shortid' ); console.log(shortId.generate()); // PPBqWA9 |
More
What really caught my eye was the custom implementation of random
.
1
2
3
4
5
6
|
var seed = 1; function random() { seed = (seed * 9301 + 49297) % 233280; return seed/(233280.0); }; |
Here’s a JSFiddle to play around with it. It works…
It got me very curious as to what it actually does as it’s not obvious to me at first glance. I found a decent article talking about this function. Turns out this function is meant to generate predictable “random” numbers based on the seed.
Digging a little bit further, I found this post from the past days:
… horrible random (sic) number generators are used by people who don’t know better, while very good ones take less than 20 lines of Pascal! Amoung the horrid generators are some that come with certain systems or are presented in textbooks!
…
Simple (bad) Psuedo Random Number Generator (Sic)
The low bit typically just toggles between calls.“`javascript
random() {
seed = ( seed * mulitiplier + increment ) % modulus;
return seed;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<br>and then later >```javascript /* > ** Dr. Park's algorithm published in the Oct. '88 ACM > ** "Random Number Generators: Good Ones Are Hard To Find" > ** His version available at ftp://cs.wm.edu/pub/rngs.tar > ** This is called a Lehmer Generator > */ > > static long Seed = 1; /* This is required to be 32 bits long */ > > long random() > /* > ** Random number between 0 and 2147483647 (2**31 - 1) inclusive > **/ > { > a = 48271 > m = 2147483647 > r = 3399 /* r = m mod a */ > q = 44488 /* q = m div a */ > if ((Seed = Seed % q * a - Seed / q * r) < 0) > Seed += m; > return Seed - 1; > } |
Here’s a JavaScript implementation:
Should the function in shortId be patched? Thoughts?