stylelint
Version:
A mighty, modern CSS linter.
103 lines (90 loc) • 2.96 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = matchesStringOrRegExp;
/**
* Compares a string to a second value that, if it fits a certain convention,
* is converted to a regular expression before the comparison.
* If it doesn't fit the convention, then two strings are compared.
*
* Any strings starting and ending with `/` are interpreted
* as regular expressions.
*
* @param {string|array} input
* @param {string|regexp|array} comparison
* @return {boolean|object} `false` if no match is found.
* If a match is found, returns an object with these properties:
* - `match`: the `input` value that had a match
* - `pattern`: the `comparison` pattern that had a match
*/
function matchesStringOrRegExp(input, comparison) {
if (!Array.isArray(input)) {
return testAgainstStringOrArray(input, comparison);
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var inputItem = _step.value;
var testResult = testAgainstStringOrArray(inputItem, comparison);
if (testResult) {
return testResult;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return false;
}
function testAgainstStringOrArray(value, comparison) {
if (!Array.isArray(comparison)) {
return testAgainstString(value, comparison);
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = comparison[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var comparisonItem = _step2.value;
var testResult = testAgainstString(value, comparisonItem);
if (testResult) {
return testResult;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return false;
}
function testAgainstString(value, comparison) {
var comparisonIsRegex = comparison[0] === "/" && comparison[comparison.length - 1] === "/";
if (comparisonIsRegex) {
var valueMatches = new RegExp(comparison.slice(1, -1)).test(value);
return valueMatches ? { match: value, pattern: comparison } : false;
}
return value === comparison ? { match: value, pattern: comparison } : false;
}