Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance improvements and internal simplification #22

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 30 additions & 76 deletions index.js
Original file line number Diff line number Diff line change
@@ -9,6 +9,8 @@

const isNumber = (v) => (typeof v === "number" && v - v === 0) || (typeof v === "string" && Number.isFinite(+v) && v.trim() !== "");

const paddingRegex = /^-?(0+)\d/;

const toRegexRange = (min, max, options) => {
if (isNumber(min) === false) {
throw new TypeError('toRegexRange: expected the first argument to be a number');
@@ -24,14 +26,10 @@ const toRegexRange = (min, max, options) => {

let opts = { relaxZeros: true, ...options };
if (typeof opts.strictZeros === 'boolean') {
opts.relaxZeros = opts.strictZeros === false;
opts.relaxZeros = !opts.strictZeros;
}

let relax = String(opts.relaxZeros);
let shorthand = String(opts.shorthand);
let capture = String(opts.capture);
let wrap = String(opts.wrap);
let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
const cacheKey = min + ':' + max + '=' + String(opts.relaxZeros) + String(opts.shorthand) + String(opts.capture) + String(opts.wrap);

if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
return toRegexRange.cache[cacheKey].result;
@@ -41,17 +39,11 @@ const toRegexRange = (min, max, options) => {
let b = Math.max(min, max);

if (Math.abs(a - b) === 1) {
let result = min + '|' + max;
if (opts.capture) {
return `(${result})`;
}
if (opts.wrap === false) {
return result;
}
return `(?:${result})`;
const result = min + '|' + max;
return opts.capture ? `(${result})` : opts.wrap ? `(?:${result})` : result;
}

let isPadded = hasPadding(min) || hasPadding(max);
let isPadded = paddingRegex.test(min) || paddingRegex.test(max);
let state = { min, max, a, b };
let positives = [];
let negatives = [];
@@ -73,7 +65,11 @@ const toRegexRange = (min, max, options) => {

state.negatives = negatives;
state.positives = positives;
state.result = collatePatterns(negatives, positives, opts);
state.result = [
...filterPatterns(negatives, positives, '-', false, opts),
...filterPatterns(negatives, positives, '-?', true, opts),
...filterPatterns(positives, negatives, '', false, opts),
].join('|');

if (opts.capture === true) {
state.result = `(${state.result})`;
@@ -85,14 +81,6 @@ const toRegexRange = (min, max, options) => {
return state.result;
};

function collatePatterns(neg, pos, options) {
let onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
let onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
let intersected = filterPatterns(neg, pos, '-?', true, options) || [];
let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
return subpatterns.join('|');
}

function splitToRanges(min, max) {
let nines = 1;
let zeros = 1;
@@ -114,9 +102,7 @@ function splitToRanges(min, max) {
stop = countZeros(max + 1, zeros) - 1;
}

stops = [...stops];
stops.sort(compare);
return stops;
return Array.from(stops).sort((a, b) => a - b);
}

/**
@@ -131,8 +117,10 @@ function rangeToPattern(start, stop, options) {
return { pattern: start, count: [], digits: 0 };
}

let zipped = zip(start, stop);
let digits = zipped.length;
const zipped = [];
for (let i = 0; i < start.length; i++) zipped.push([start[i], stop[i]]);

const digits = zipped.length;
let pattern = '';
let count = 0;

@@ -143,7 +131,7 @@ function rangeToPattern(start, stop, options) {
pattern += startDigit;

} else if (startDigit !== '0' || stopDigit !== '9') {
pattern += toCharacterClass(startDigit, stopDigit, options);
pattern += `[${startDigit}${(stopDigit - startDigit === 1) ? '' : '-'}${stopDigit}]`;

} else {
count++;
@@ -158,10 +146,8 @@ function rangeToPattern(start, stop, options) {
}

function splitToPatterns(min, max, tok, options) {
let ranges = splitToRanges(min, max);
let tokens = [];
let start = min;
let prev;
const tokens = [], ranges = splitToRanges(min, max);
let prev, start = min;

for (let i = 0; i < ranges.length; i++) {
let max = ranges[i];
@@ -192,43 +178,21 @@ function splitToPatterns(min, max, tok, options) {
return tokens;
}

function filterPatterns(arr, comparison, prefix, intersection, options) {
let result = [];
function filterPatterns(arr, comparison, prefix, intersection) {
const result = [];

for (let ele of arr) {
let { string } = ele;
for (const { string } of arr) {
const contained = comparison.some(ele => ele.string === string);

// only push if _both_ are negative...
if (!intersection && !contains(comparison, 'string', string)) {
// only push if _both_ are negative or positive
if (intersection === contained) {
result.push(prefix + string);
}

// or _both_ are positive
if (intersection && contains(comparison, 'string', string)) {
result.push(prefix + string);
}
}
return result;
}

/**
* Zip strings
*/

function zip(a, b) {
let arr = [];
for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
return arr;
}

function compare(a, b) {
return a > b ? 1 : b > a ? -1 : 0;
}

function contains(arr, key, val) {
return arr.some(ele => ele[key] === val);
}

function countNines(min, len) {
return Number(String(min).slice(0, -len) + '9'.repeat(len));
}
@@ -237,29 +201,19 @@ function countZeros(integer, zeros) {
return integer - (integer % Math.pow(10, zeros));
}

function toQuantifier(digits) {
let [start = 0, stop = ''] = digits;
if (stop || start > 1) {
return `{${start + (stop ? ',' + stop : '')}}`;
}
return '';
}
function toQuantifier([start = 0, stop = '']) {

function toCharacterClass(a, b, options) {
return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
}
return (stop || start > 1) ? `{${start + (stop ? ',' + stop : '')}}` : '';

function hasPadding(str) {
return /^-?(0+)\d/.test(str);
}

function padZeros(value, tok, options) {
if (!tok.isPadded) {
return value;
}

let diff = Math.abs(tok.maxLen - String(value).length);
let relax = options.relaxZeros !== false;
const diff = Math.abs(tok.maxLen - String(value).length);
const relax = !!options.relaxZeros !== false;

switch (diff) {
case 0: