I'm trying to do addition with human words. My code takes the input, slices every word, and pushes into an array called DL. This works without any issues, and if you console.log it out, it does this:
[ 'add' ]
[ 'add', '6' ]
[ 'add', '6', 'and' ]
[ 'add', '6', 'and', '4' ]
Now I have an array in the code that are supposed to act as 'operators'. It looks like this:
var operator = [
"add",
"sub",
"mul",
"div"
]
Now I want to loop through the DL array to see if one of the operators is in DL. If this case passes true, I want to add 6 and 4 together, and the code will print out 10.
This is the full code:
function output(func) {
console.log(func)
}
var operator = [
"add",
"sub",
"mul",
"div"
]
var dl = []
const read = string => {
return string.split(' ').map(item => {
dl.push(item.trim())
console.log(dl)
})
}
var main = read(
`add 6 and 4`
)
output(main)
first, separate the operators and numbers from the array , you can either separate these two inside a .map or use a separate .filter
const operator = dl.find(x=>x.includes("add" , "sub" , "mul", "del"))
const numbers = dl.filter(x=>Number(x))
then use a separate function to do the operations like
console.log(output())
function output(){
switch(operator){
case "add":
return numbers.reduce((a, b) => Number(a) +Number(b));
case "sub":
// your logic here
// rest of the operators logic
}
}