From 79a5f61468594951a0637b5f1784a173165b5d6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Unneb=C3=A4ck?= Date: Fri, 20 Oct 2023 21:54:37 +0200 Subject: [PATCH] perf: optimize code even further (#40) --- index.js | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index 38eaa73..f489323 100644 --- a/index.js +++ b/index.js @@ -1,20 +1,22 @@ 'use strict' -module.exports = (function (array) { - return function luhn (number) { - if (typeof number !== 'string') throw new TypeError('Expected string input') - if (!number) return false - let length = number.length - let bit = 1 - let sum = 0 - let value +const lookup = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] - while (length) { - value = parseInt(number.charAt(--length), 10) - bit ^= 1 - sum += bit ? array[value] : value - } +module.exports = function luhn (number) { + if (typeof number !== 'string') throw new TypeError('Expected string input') + if (!number) return false - return sum % 10 === 0 + let index = number.length + let x2 = true + let sum = 0 + + while (index) { + const value = number.charCodeAt(--index) - 48 + if (value < 0 || value > 9) return false + + x2 = !x2 + sum += x2 ? lookup[value] : value } -}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9])) + + return sum % 10 === 0 +}