Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
Trying to add more cases, not working as intended

My goal is to make a little program that understands human words, and it's going great so far thanks to a little help.

I decided to start out with simple math before making other stuff but something is wrong.

So far the human reader can do addition, but I want it do more operations like subtraction, multiplication, division, etc. I have this part of the code that handles cases, basically if you tell it to 'add ...' it should add, you get the idea, And it looks like this:

switch (operator) {
    case "add":
      return numbers.reduce((a, b) => Number(a) + Number(b));

Great, so I figured I should just make another case and just do "subtract" and just do Number(a) - Number(b) right?

Well thats where it goes flop, if I tell it to subtract 2 from 5, it gives me a response that looks like this:

undefined

When what I want it to say is:

-3

How can I solve this issue? Full Source Code:

function output(func) {
  console.log(func)
}

function read(str) {
  const dl = str.split(' ');
  const operator = dl.shift(x => x.includes("add", "sub", "mul", "div"))
  const numbers = dl.filter(x => Number(x))
  switch (operator) {
    case "add":
      return numbers.reduce((a, b) => Number(a) + Number(b));
    case "subtract":
      return numbers.reduce((a, b) => Number(a) - Number(b));
  }
}

const result = read(
  "add 6 and 4"
)

output(result)
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Looks like it works fine.

function output(func) {
  console.log(func)
}

function read(str) {
  const dl = str.split(' ');
  const operator = dl.shift(x => x.includes("add", "sub", "mul", "div"))
  const numbers = dl.filter(x => Number(x))
  switch (operator) {
    case "add":
      return numbers.reduce((a, b) => Number(a) + Number(b));
    case "subtract":
      return numbers.reduce((a, b) => Number(a) - Number(b));
  }
}

output(read(
  "add 6 and 4"
))

output(read(
  "subtract 6 and 4"
))

output(read(
  "subtract 2 and 5"
))

output(read(
  "sub 2 and 5"
))

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda