Skip to content

Commit d227166

Browse files
omgovichVlad Shilov
authored andcommitted
Optimize getRandomChar and produce
1 parent 659111a commit d227166

File tree

3 files changed

+11
-11
lines changed

3 files changed

+11
-11
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
A tiny memorable password generator
66

7-
- **Fast**: 16 times faster than `password-generator`
8-
- **Small**: 342 bytes (minified and gzipped)
7+
- **Fast**: 600 times faster than `password-generator`
8+
- **Small**: 334 bytes (minified and gzipped)
99
- **Safe**: Uses [cryptographically strong random API](https://nodejs.org/api/crypto.html) instead of `Math.random`
1010
- **No dependencies**
1111
- Supports Node.js and browsers

index.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,25 +37,25 @@ const getRandomSyllable = ({
3737
return syllable;
3838
};
3939

40-
const getRandomChar = stack => {
41-
return stack.charAt(random(stack.length));
42-
};
40+
const getRandomChar = stack => stack[random(stack.length)];
4341

4442
const produce = (number, callback) => {
45-
let result = "";
46-
for (let index = 0; index < number; index++) result += callback(index);
43+
for (var index = 0, result = ""; index < number; index++) {
44+
result += callback(index);
45+
}
46+
4747
return result;
4848
};
4949

5050
let buffer = [];
5151
let bufferSize = 0xffff;
52-
let bufferIndex = bufferSize + 1;
52+
let bufferIndex = bufferSize;
5353

5454
const random = limit => {
55-
if (++bufferIndex > bufferSize) {
55+
if (bufferIndex >= bufferSize) {
5656
buffer = getRandomValues(bufferSize);
5757
bufferIndex = 0;
5858
}
5959

60-
return buffer[bufferIndex] % limit;
60+
return buffer[bufferIndex++] % limit;
6161
};

test/benchmark.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const libraries = [
1111
name: "omgopass",
1212
browser: true,
1313
node: true,
14-
size: 342,
14+
size: 334,
1515
generate: () => omgopass()
1616
},
1717
{

0 commit comments

Comments
 (0)