Skip to content

Commit

Permalink
fix: first check if string is ASCII
Browse files Browse the repository at this point in the history
  • Loading branch information
sosukesuzuki committed Sep 23, 2022
1 parent 04802f9 commit a6beb2e
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions lib/rules/id-length.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,44 @@
//------------------------------------------------------------------------------
const GraphemeSplitter = require("grapheme-splitter");

const splitter = new GraphemeSplitter();
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
* Checks if the string given as argument is ASCII or not.
* @param {string} value A string that you want to know if it is ASCII or not.
* @returns {boolean} `true` if `value` is ASCII string.
*/
function isASCII(value) {
if (typeof value !== "string") {
return false;
}
for (let i = 0; i < value.length; i++) {
if (value.charCodeAt(i) > 127) {
return false;
}
}
return true;
}

/** @type {GraphemeSplitter | undefined} */
let splitter;

/**
* Gets the length of the string. If the string is not in ASCII, counts graphemes.
* @param {string} value A string that you want to get the length.
* @returns {number} The length of `value`.
*/
function getStringLength(value) {
if (isASCII(value)) {
return value.length;
}
if (!splitter) {
splitter = new GraphemeSplitter();
}
return splitter.countGraphemes(value);
}

//------------------------------------------------------------------------------
// Rule Definition
Expand Down Expand Up @@ -137,7 +174,7 @@ module.exports = {
const name = node.name;
const parent = node.parent;

const nameLength = splitter.countGraphemes(name);
const nameLength = getStringLength(name);

const isShort = nameLength < minLength;
const isLong = nameLength > maxLength;
Expand Down

0 comments on commit a6beb2e

Please sign in to comment.