Range Tests

Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)

    test markup, will be hidden

    Test


    test("toRange has the proper interface", function() {
        equals(typeof toRange, "function", "'toRange' should be a function");
    });

    test("toRange generates proper ranges for single-digit integers", function() {
        equals(toRange(9), "(?:\\d)", "'toRange' should return '\\d' for value of 9");
    });

    test("toRange generates proper ranges for double-digit integers", function() {
        equals(toRange(20), "(?:\\d|1\\d|20)", "'toRange' should return simple regex for 0 - 20");
    });

    test("More complicated ranges are generated properly", function() {
       equals(toRange(267, 4301), "(?:26[7-9]|2[7-9]\\d|[3-9]\\d\\d|[1-3]\\d\\d\\d|4[0-2]\\d\\d|430[0-1])",
      "Complex ranges should work.")
    });
      

    Code


    var toRange = (function() {
        function range(vals) {
            var parts = vals.split("-"), start = parts[0], end = parts[1], match;
            if (start === end) {
                return start;
            } else if (start.length <  end.length) {
                return range(start + "-" + start.replace(/\d/g, "9")) + "|" +
                       range("1" + start.replace(/\d/g, "0") + "-" + end);
            } else if (match = /^(\d*)(\d)(0*)\-\1(\d)9*$/.exec(vals)) {
                return match[1] + ((match[2] === "0" && match[4] === "9") ? "\\d" :
                       ("[" + match[2] + "-" + match[4]) + "]" + match[3].replace(/0/g, "\\d"));
            } else if (match = /^(\d*)(\d)\d*\-\1(\d)9(9*)$/.exec(vals)) {
                return range(start + "-" + match[1] + match[2] + "9" + match[4]) + "|" +
                       range(match[1] + (1 + Number(match[2])) + "0" + match[4].replace(/9/g, "0") + "-" + end);
            } else if (match = /^(\d*)(\d+)\-\1(\d)(\d*)$/.exec(vals)) {
                return range(start + "-" + match[1] + (Number(match[3]) - 1) + match[4].replace(/\d/g, "9")) + "|" +
                       range(match[1] + match[3] + match[4].replace(/\d/g, "0") + "-" + end)
            } else  if (match = /^(\d*)(\d)\-\1(\d)$/.exec(vals)) {
                return match[1] + "[" + match[2] + "-" + match[3] + "]";
            }
            return ""; // throw error?
        }

        return function(start, end) {
            if (arguments.length < 1) {return "";} // throw error?
            if (arguments.length == 1) {return "(?:" + range("0-" + start) + ")";}
            if (start > end) {return "";} // throw error?

            return "(?:" + range("" + start + "-" + end) + ")";
        };
    }());