Skip to content

Latest commit

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..

README.md

Reto #28: Expresi贸n matem谩tica

Enunciado

Crea una funci贸n que reciba una expresi贸n matem谩tica (String) y compruebe si es correcta. Retornar谩 true o false.

  • Para que una expresi贸n matem谩tica sea correcta debe poseer un n煤mero, una operaci贸n y otro n煤mero separados por espacios. Tantos n煤meros y operaciones como queramos.
  • N煤meros positivos, negativos, enteros o decimales.
  • Operaciones soportadas: + - * / %

Ejemplos:

"5 + 6 / 7 - 4" -> true
"5 a 6" -> false

My solution

const isMathExpresion = (str) => {
  str = str.replace(/\s+/g, ' ').split(' ').join('');
  const regex = /^(\d+[\\+\-\\*\\/%]?)+\d+$/;
  return regex.test(str);
};

Explanation of my solution

isMathExpresion function

  • First, I declare a function named isMathExpresion that receives a parameter named str.
const isMathExpresion = (str) => {
  • Then, I replace all the spaces in the str parameter with a single space.
  str = str.replace(/\s+/g, ' ');
  • Then, I split the str parameter by spaces and join the resulting array into a string.
  str = str.replace(/\s+/g, ' ').split(' ').join('');
  • Then, I declare a variable named regex that will store a regular expression that will be used to test if the str parameter is a valid mathematical expression.
  const regex = /^(\d+[\\+\-\\*\\/%]?)+\d+$/;
  • The regular expression stored in the regex variable will match the following:

    • ^: The beginning of the string.
    • (: The beginning of a capturing group.
    • \d+: One or more digits.
    • [\\+\-\\*\\/%]?: An optional +, -, *, / or % character.
    • ): The end of the capturing group.
    • +: One or more times.
    • \d+: One or more digits.
    • $: The end of the string.
  • Then, I return the result of testing if the str parameter matches the regular expression stored in the regex variable.

  return regex.test(str);
};
  • The test method of the RegExp object receives a string as a parameter and returns true if the string matches the regular expression, or false otherwise.