Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Last active March 31, 2020 18:01
Show Gist options
  • Save shiracamus/98a767b19f79cf826bfbfc30aca6bf53 to your computer and use it in GitHub Desktop.
Save shiracamus/98a767b19f79cf826bfbfc30aca6bf53 to your computer and use it in GitHub Desktop.
function iter(pattern) {
let index = 0
return {
[Symbol.iterator]: function() { return this },
next: function() {
if (index < pattern.length)
return { value: pattern[index++], done: false }
else
return { done: true }
},
fetch: function() { return pattern[index] },
}
}
function charset(pattern, exclude = '') {
function* chars() {
let start = null
const p = iter(pattern)
for (let c of p) {
if (c === '-' && start && p.fetch()) {
const { value } = p.next()
const end = value.charCodeAt(0)
for (let code = start + 1; code <= end; code++)
yield String.fromCharCode(code)
start = null
} else {
if (c === '\\' && p.fetch())
( { value: c } = p.next() )
yield c
start = c.charCodeAt(0)
}
}
}
return [...chars()].filter(c => !exclude.includes(c)).join('')
}
const PATTERNS = {
b: '01',
o: charset('0-7'),
d: charset('0-9'),
X: charset('0-9A-F'),
x: charset('0-9a-f'),
A: charset('A-Za-z'),
C: charset('A-Z'),
c: charset('a-z'),
B: 'AEIOUaeiou',
V: 'AEIOU',
v: 'aeiou',
D: charset('A-Za-z', 'AEIOUaeiou'),
Q: charset('A-Z', 'AEIOU'),
q: charset('a-z', 'aeiou'),
Y: charset('0-9A-Za-z'),
Z: charset('0-9A-Z'),
z: charset('0-9a-z'),
W: charset('0-9A-Za-z_'),
L: charset('0-9A-Z_'),
l: charset('0-9a-z_'),
}
console.log(PATTERNS)
console.log(PATTERNS['D'])
console.log(charset('0\\-9'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment