Skip to content

Instantly share code, notes, and snippets.

@Nick-Gabe
Last active March 18, 2023 13:02
Show Gist options
  • Save Nick-Gabe/ca65b5842bcb3530b0bd99fed7720efc to your computer and use it in GitHub Desktop.
Save Nick-Gabe/ca65b5842bcb3530b0bd99fed7720efc to your computer and use it in GitHub Desktop.
Function to compare multiple numbers using greater (<) and smaller (>) logic.
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