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)
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"
))