Skip to content

Instantly share code, notes, and snippets.

@carlosvega20
Created November 3, 2023 08:33
Show Gist options
  • Save carlosvega20/8ec8b472de22626a70a65f5893de82e9 to your computer and use it in GitHub Desktop.
Save carlosvega20/8ec8b472de22626a70a65f5893de82e9 to your computer and use it in GitHub Desktop.
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'
@carlosvega20
Copy link
Author

carlosvega20 commented Nov 3, 2023

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