Last active
March 18, 2023 13:02
-
-
Save Nick-Gabe/ca65b5842bcb3530b0bd99fed7720efc to your computer and use it in GitHub Desktop.
Function to compare multiple numbers using greater (<) and smaller (>) logic.
This file contains hidden or 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
function compareNums(comparison) { | |
if (!comparison) return false; | |
const validFormat = /\d+(([<>]=*)\d+)*/; | |
const removeSpaces = str => str.replace(/\s/g, ''); | |
comparison = removeSpaces(comparison); | |
const [match] = comparison.match(validFormat); | |
if (match.length !== comparison.length) { | |
throw new Error('invalid format: the format should match x < y < z...'); | |
} | |
const comparisonParts = comparison.match(/(\d+)|([<>]=*)/g); | |
for (let i = 0; i < comparisonParts.length; i += 2) { | |
const [ | |
firstNumber, | |
operator, | |
secNumber | |
] = comparisonParts.slice(i, i + 3); | |
if (operator === '>' && | |
!(Number(firstNumber) > Number(secNumber)) || | |
operator === '<' && | |
!(Number(firstNumber) < Number(secNumber)) || | |
operator === '<=' && | |
!(Number(firstNumber) <= Number(secNumber)) || | |
operator === '>=' && | |
!(Number(firstNumber) >= Number(secNumber)) | |
) { | |
return false | |
} | |
} | |
return true | |
} | |
// Examples of the function | |
console.log(`1. ${compareNums('10 < 15 < 20')}`); // true | |
console.log(`2. ${compareNums('10 >= 10')}`); // true | |
console.log(`3. ${compareNums('5 > 4 > 3 > 2 > 1 > 0')}`); // true | |
console.log(`4. ${compareNums('10 > 100')}`); // false | |
console.log(`5. ${compareNums('10 > 10')}`); // false | |
const variable = 5; | |
console.log(`6. ${compareNums(`1 < ${variable} < 10`)}`); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment