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

isISIN optimization #1633

Merged
merged 3 commits into from
Apr 17, 2021
Merged
Show file tree
Hide file tree
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
57 changes: 40 additions & 17 deletions src/lib/isISIN.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,57 @@ import assertString from './util/assertString';

const isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;

// this link details how the check digit is calculated:
// https://www.isin.org/isin-format/. it is a little bit
// odd in that it works with digits, not numbers. in order
// to make only one pass through the ISIN characters, the
// each alpha character is handled as 2 characters within
// the loop.

export default function isISIN(str) {
assertString(str);
if (!isin.test(str)) {
return false;
}

const checksumStr = str.replace(/[A-Z]/g, character => (parseInt(character, 36)));

let double = true;
let sum = 0;
let digit;
let tmpNum;
let shouldDouble = true;
for (let i = checksumStr.length - 2; i >= 0; i--) {
digit = checksumStr.substring(i, (i + 1));
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum + 1;
} else {
sum += tmpNum;
// convert values
for (let i = str.length - 2; i >= 0; i--) {
if (str[i] >= 'A' && str[i] <= 'Z') {
const value = str[i].charCodeAt(0) - 55;
const lo = value % 10;
const hi = Math.trunc(value / 10);
// letters have two digits, so handle the low order
// and high order digits separately.
for (const digit of [lo, hi]) {
if (double) {
if (digit >= 5) {
sum += 1 + ((digit - 5) * 2);
} else {
sum += digit * 2;
}
} else {
sum += digit;
}
double = !double;
}
} else {
sum += tmpNum;
const digit = str[i].charCodeAt(0) - '0'.charCodeAt(0);
if (double) {
if (digit >= 5) {
sum += 1 + ((digit - 5) * 2);
} else {
sum += digit * 2;
}
} else {
sum += digit;
}
double = !double;
}
shouldDouble = !shouldDouble;
}

return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10;
const check = (Math.trunc(((sum + 9) / 10)) * 10) - sum;

return +str[str.length - 1] === check;
}
1 change: 1 addition & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -4683,6 +4683,7 @@ describe('Validators', () => {
'GB0001411924',
'DE000WCH8881',
'PLLWBGD00016',
'US0378331005',
],
invalid: [
'DE000BAY0018',
Expand Down