Skip to content

Commit

Permalink
(fix): validator method
Browse files Browse the repository at this point in the history
  • Loading branch information
JuanMaRuiz committed Sep 28, 2021
1 parent 99d8d4a commit 121f2be
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
3 changes: 1 addition & 2 deletions __test__/validator.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import validate from './../src/validator.js';

// Valid ISBN 8497364678, 84-481-2231-3, 978-84-415-2682-2

test('validate method should return TRUE if passed value is a valid 10 numbers ISBN ', () => {
expect(validate('84 - 481 - 2231 - 3')).toBe(true);
expect(validate('84 - 481 2231- 3')).toBe(true);
Expand All @@ -20,6 +18,7 @@ test('validate method should return FALSE if passed string does not have the cor
test('validate method should return TRUE if passed value is a valid 13 numbers ISBN ', () => {
expect(validate('978-84-415-2682-2')).toBe(true);
expect(validate('978-34-2628-155-0')).toBe(true);
expect(validate('978-2-27-509083-2')).toBe(true);
});

test('validate method should return FALSE if passed value is NOT a valid 13 numbers ISBN ', () => {
Expand Down
10 changes: 8 additions & 2 deletions src/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const IsValidIsbn = isbn => {
result = controlDigit.toUpperCase() === 'X' ? modulus === 10 : modulus === parseInt(controlDigit);

} else {
const elementsSum = isbnAsArray.map((el, index) => (index + 1) % 2 === 0 ? el * 1 : el * 3).reduce((acc, curr) => acc + curr);
const elementsSum = isbnAsArray.map((el, index) => index % 2 === 0 ? el * 1 : el * 3).reduce((acc, curr) => acc + curr);

result = getControlDigit(elementsSum) === parseInt(controlDigit);
}
Expand All @@ -30,7 +30,13 @@ const IsValidIsbn = isbn => {
};

const getControlDigit = (sum, acc = 0) => {
return sum % 10 !== 0 ? getControlDigit(sum + 1, acc + 1) : acc;
if (sum % 10 !== 0) {
return getControlDigit(sum + 1, acc + 1);
} else if (sum % 10 === 0 && acc === 0) {
return 0;
} else {
return acc;
}
};

const validate = (isbn) => {
Expand Down

0 comments on commit 121f2be

Please sign in to comment.