Created
November 3, 2023 08:33
-
-
Save carlosvega20/8ec8b472de22626a70a65f5893de82e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getTree = barcode => { | |
const barcodeLength = barcode.length; | |
const firstTwoDigits = parseInt(barcode.slice(0,2)); | |
const dic = { | |
'bluecypress': {digits: [45,56], length: 8, name: 'Blue Ice Arizona Cypress'}, | |
'palm': {digits: [76, 43], length: 12, name: 'The Palm Tree'}, | |
'maple': {digits: [23, 12,45,54], length: 6, name: 'Maple Trees'} | |
}; | |
const [_, {name}] = Object.entries(dic).find(([key, {digits, length}])=> | |
digits.includes(firstTwoDigits) && length===barcodeLength | |
); | |
return name; | |
}; | |
getTree('545456'); //Maple Trees | |
//Initial Approach | |
// const getTree = (barcode) => { | |
// const dic = {'bluecypress': {digits: [45,56], length: 8}, 'palm': {digits: [76, 43], length: 12}, 'error': 'Not Found'}; | |
// const names = {'bluecypress': 'Blue Ice Arizona Cypress', 'palm': 'The Palm Tree'}; | |
// const code = [...Object.keys(dic)].find(key=> { | |
// const [first, second] = dic[key].digits; | |
// const digits = barcode.slice(0,2); | |
// return digits===`${first}` || digits === `${second}`; | |
// }); | |
// if(dic[code].length === barcode.length) { | |
// return names[code]; | |
// } else { | |
// return dic['error'] | |
// } | |
// } | |
// getTree('76435235345'); //It should return 'The Palm Tree' | |
Improving performance
const getCreditCard = number => {
const size = number.length;
const dic = [
{digits: /^(37|34)/, lengths: /^.{15}$/, name: 'American Express'},
{digits: /^4/, lengths: /^(.{13}|.{16}|.{19})$/, name: 'Visa Card'},
{digits: /^[25]/, lengths: /^.{16}$/, name: 'Mastercard Card'},
{digits: /^(6011|644|645|646|647|648|649|65)/, lengths: /^.{16,19}$/, name: 'Discover Card'}
];
const checkType = (cardNumber) => {
return dic.find( type => type['digits'].test(cardNumber) && type['lengths'].test(cardNumber))
};
return checkType(number)?.name;
};
getCreditCard('379765455453372'); //American Express
My own implementation of the Luhn Algorithm (based on https://en.wikipedia.org/wiki/Luhn_algorithm):
const checkLuhn = cardNumber => {
const sum = [...cardNumber].reduceRight((prev, curr, i, arr) =>
prev+= (i%2)?Number(arr[Number(curr)]):Number(curr)
,0);
return sum && sum % 10 === 0;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then I was asked: to support multiple lengths and also digits can have different lengths.