• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

webboot / crypto / 40

pending completion
40

push

travis-ci-com

jaeh
format

35 of 38 branches covered (92.11%)

Branch coverage included in aggregate %.

68 of 68 new or added lines in 3 files covered. (100.0%)

7934 of 8167 relevant lines covered (97.15%)

2.04 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

17.57
/src/random/number.mjs
1
import crypto from 'crypto'
2✔
2

2✔
3
const libName = '@webboot/crypto.random.number'
2✔
4

2✔
5
const defaultArgs = {
2✔
6
  min: 0,
2✔
7
  max: 281474976710654,
2✔
8
}
2✔
9

2✔
10
export const number = async params => {
2✔
11
  try {
×
12
    const options = Object.assign({}, defaultArgs, params)
×
13
    let { min, max } = options
×
14

×
15
    const distance = max - min
×
16

×
17
    if (min > max) {
×
18
      const m = min
×
19
      min = max
×
20
      max = m
×
21
    }
×
22

×
23
    if (max > Number.MAX_SAFE_INTEGER) {
×
24
      throw new Error(
×
25
        `${libName}: Max number should be Number.MAX_SAFE_INTEGER too high by: ${
×
26
          max - Number.MAX_SAFE_INTEGER
×
27
        }`,
×
28
      )
×
29
    }
×
30

×
31
    if (distance > 281474976710655) {
×
32
      throw new Error(`${libName}: Distance is greater than 256^6-1 ${distance}`)
×
33
    }
×
34

×
35
    let subOnEnd = 0
×
36
    if (min < 0) {
×
37
      subOnEnd = min
×
38
      max += Math.abs(min)
×
39
      min = 0
×
40
    }
×
41

×
42
    let maxBytes = 6
×
43
    let maxDec = 281474976710656
×
44

×
45
    // Adjust maxBytes for small ranges
×
46
    if (distance < 256) {
×
47
      maxBytes = 1
×
48
      maxDec = 256
×
49
    } else if (distance < 65536) {
×
50
      maxBytes = 2
×
51
      maxDec = 65536
×
52
    } else if (distance < 16777216) {
×
53
      maxBytes = 3
×
54
      maxDec = 16777216
×
55
    } else if (distance < 4294967296) {
×
56
      maxBytes = 4
×
57
      maxDec = 4294967296
×
58
    } else if (distance < 1099511627776) {
×
59
      maxBytes = 4
×
60
      maxDec = 1099511627776
×
61
    }
×
62

×
63
    const byteString = await crypto.randomBytes(maxBytes).toString('hex')
×
64
    const randbytes = parseInt(byteString, 16)
×
65

×
66
    return Math.min(max, Math.floor((randbytes / maxDec) * (max - min + 1) + min + subOnEnd))
×
67
  } catch (e) {
×
68
    e.message = `${libName} ${e.message}`
×
69
    throw e
×
70
  }
×
71
}
×
72

2✔
73
export default number
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2023 Coveralls, Inc