Skip to content

Instantly share code, notes, and snippets.

@puzpuzpuz
Last active November 16, 2020 07:59
Show Gist options
  • Save puzpuzpuz/4618459e6508736b5b413ad6b5bd3908 to your computer and use it in GitHub Desktop.
Save puzpuzpuz/4618459e6508736b5b413ad6b5bd3908 to your computer and use it in GitHub Desktop.
check-is-http-token.js
'use strict'
const keys = [
'TCN',
'alternate-protocol',
':',
'@@',
'中文呢',
'((((())))',
':alternate-protocol',
'alternate-protocol:',
]
const randKeysPoolSize = 1e6
const randKeysPool = []
// #1 Random selection:
for (let i = 0; i < randKeysPoolSize; i++) {
const idx = Math.floor(Math.random() * Math.floor(keys.length))
randKeysPool.push(keys[idx])
}
// #2 Predictable selection:
// let pos = 0
// for (let i = 0; i < randKeysPoolSize; i++) {
// const idx = pos++ % keys.length
// randKeysPool.push(keys[idx])
// }
function loopBasedCheck(val) {
if (val.length === 0) {
return false
}
// Character check based off of previous regex:
// /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
for (let i = 0; i < val.length; i++) {
const cc = val.charCodeAt(i)
if (
(cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90) || // A-z
cc === 45 || // -
cc === 33 || // !
(cc >= 35 && cc <= 39) || // # $ % & '
cc === 42 || // *
cc === 43 || // +
cc === 46 || // .
(cc >= 48 && cc <= 57) || // 0-9
(cc >= 94 && cc <= 96) || // ^ _ `
cc === 124 || // |
cc === 126 // ~
) {
continue
} else {
return false
}
}
return true
}
let iterations = 0
const Benchmark = require('benchmark')
const suite = new Benchmark.Suite()
suite
.add(
'loop',
() => {
const idx = iterations++ % randKeysPoolSize
return loopBasedCheck(randKeysPool[idx])
}
)
suite
.on('cycle', function (event) {
console.log(String(event.target))
})
.on('complete', function () {
console.log('Benchmark is complete')
})
.run({ 'async': false })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment