Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!