To answer last week’s POW, the purpose of the SQL was to generate a random string of letters and numbers. I actually wrote two different JavaScript function that can produce the same results. The following is the slightly more straight-forward solution:

```
function randomChars(len) {
for(var n, s = ""; --len;) {
n = parseInt(Math.random() * 62);
s = String.fromCharCode(n + (n < 26 ? 65 : n < 52 ? 71 : -4));
}
return s;
}
```

The next version is a bit harder to follow because it involves recursion:

```
function recRandomChars(len) {
if(!len){ return ""; }
var n = parseInt(Math.random() * 62);
return recRandomChars(--len)
+ String.fromCharCode(n + (n < 26 ? 65 : n < 52 ? 71 : -4));
}
```

One practical application of this is to generate a password with random characters.

## 1 Comment

## POW – Explain That SQL #1 | Chris West's Blog · August 24, 2012 at 4:42 PM

[…] Post navigation ← Previous Next → […]