-1

Okay big question about switch statements. I'm new to JS.

I'm trying to make a switch statement that takes input from an input box, looks for "Multiplication" "Subtraction" "Addition" and "Division" among letters and numbers in the input string and separates non-numbers from numbers and then does the typed operation on the set of numbers. So for instance, the input box might look like this:

1 a 2 b 3 c 4 multiply d 5 e

So far, I've been able to separate numbers from non-numbers into arrays that would look like this given the input above:

numberArray === [1,2,3,4,5]
letterArray === [a,b,c,multiply,d,e]

and I have functions set to add, subtract, multiply, and divide the number array, so how would I incorporate using a switch statement to find one of those many possible inputs in my array of letters?

Another thing, all the loops used for the mathematical operations are similar, for instance, subtraction looks like this:

for (; i < numberArray.length; i++ ) {
    if (i === 0) {
        sub = numberArray[0]
    } else {
        sub = sub - numberArray[i]
    }
}

and multiplication looks like this:

   for (; i < numberArray.length; i++ ) {
    if (i === 0) {
        sub = numberArray[0];
    } else {
        sub = sub * numberArray[i];
    } 
}

Would it be possible to use the same switch statement to consolidate all four operation functions into one function, instead of calling each separate function for each case?

Edited to explain my letter and number arrays, also to change the title and tags from another topic that was entirely unrelated.

Giverbud
  • 23
  • 1
  • 7
  • Explain this `1 a 2 b 3 c 4 multiply d 5 e`!!!! What are `a`, `b`...? – ibrahim mahrir Feb 05 '17 at 00:13
  • @ibrahimmahrir here I'll edit it – Giverbud Feb 05 '17 at 00:20
  • You still didn't explain what are `a`, `b` ... – ibrahim mahrir Feb 05 '17 at 00:23
  • Hey sorry @ibrahimmahrir and RobG, I didn't realize I posted this with a title I almost used for another post a while ago, I've since edited it – Giverbud Feb 05 '17 at 00:26
  • @Giverbud What is the meaning of `a` and `b` ...? Please answer my question! `multiply` is clear but `a` and `b` what are they,? Variables? Operations? What the hell are they? – ibrahim mahrir Feb 05 '17 at 00:27
  • They're just possible inputs, so strings, I guess. I already have functions that separate the results in my input box into the two arrays I've since included in my post. So perhaps the results of the input box could look like that, I want my program to look for "multiplication", "subtraction", etc. amidst all the results in my input box so that my program knows what operation to use on the numbers put into the input box. – Giverbud Feb 05 '17 at 00:30
  • Post an example and a desired result of that example! – ibrahim mahrir Feb 05 '17 at 00:31
  • can the user type more operations like this: `12 substraction 3 multiplication 4`? – ibrahim mahrir Feb 05 '17 at 00:33
  • No, only one operation – Giverbud Feb 05 '17 at 00:33
  • Given the example input I have given above, I want to write a switch statement that recognizes the "multiplication" in the input field, recognizes the numbers, and outputs "120". I have been able to separate all numbers and letters and I've made all the mathematical operations into functions, I want to know if I can make one function that uses a switch to check for one of the operation names and then does the corresponding operation on the numbers in the input box, ignoring extra letters like a, b, etc. – Giverbud Feb 05 '17 at 00:36

2 Answers2

0

A better approach than using a switch statement would be using a callback.

function reduce(array, operation, initialValue) {
  var result = initialValue;
  // We can reuse the same for loop logic with different operations
  for (var i = 0; i < array.length; i++) {
    result = operation(result, array[i]);
  }
  return result;
}

// This is the 'operation' that will get passed in to reduce
function addition(a, b) {
  return a + b;
}

var myArray = [1, 2, 3];

console.log(reduce(myArray, addition, 0));

// You can also add it to the array prototype and call it like this:
function protoReduce(operation, initialValue) {
  var result = initialValue;
  for (var i = 0; i < this.length; i++) {
    result = operation(result, this[i]);
  }
  return result;
}

Array.prototype.reduce = protoReduce;
console.log(myArray.reduce(addition, 0));

And here is a recursive approach:

function reduce(array, operation) {
  var initialValue = array.shift();
  var result;
  if (array.length > 1) {
    result = reduce(array, operation);
  } else {
    result = array[0];
  }
  return operation(initialValue, result);
}

function addition(a, b) {
  return a + b;
}

var myArray = [1, 2, 3, 4];

console.log('result:', reduce(myArray, addition));
  • Sorry, I mistitled this post (it was actually a title that was saved from a post I almost made a while back). I don't need help with reducing, but what does a callback do? – Giverbud Feb 05 '17 at 00:28
  • Follow the flow of execution in this code. The operation was abstracted away to another function that gets passed in as an argument. –  Feb 05 '17 at 00:33
  • So do you mean calling another function? Because all my operations functions are so similar that I have a feeling I could use the small differences between them in a switch statement instead of having 4 big blocks of code just to set them as separate functions. – Giverbud Feb 05 '17 at 00:51
0
//strings === array of strings
//numbers === array of numbers

// list of all the operations and the function associated with it
var operations = {
  add: function(a, b) { return Number(a) + Number(b); },
  substract: function(a, b) { return a - b; },
  multiply: function(a, b) { return a * b; },
  divide: function(a, b) { return a / b; }
}

// check if an operation exist
var found = false;
var op;
for(op in operations) { // loop through the key of the operations object
  if(strings.indexOf(op) != -1) { // if strings contain that operation
    found = true; // then we have found one
    break; // stop the search
  }
}

if(found && numbers.length) { // if we have found an operation and there is numbers
  var result = numbers[0];
  for(var i = 1; i < numbers.length; i++) // apply the function associated with the operation on all the numbers
    result = operations[op](result, numbers[i]);
  alert(result);
}
else // if there is an error (no operation or no numbers)
  alert("no number or no operation!");

Addition explanation:

Since + is used to either sum numbers or to concatenate strings the operands of the addition should be explicitly converted to numbers using parseInt (if they're integers) or parseFloat (if they're float) or Number (if not sure) like:

return parseFloat(a) + parseFloat(b);
// or
return parseInt(a) + parseInt(b); 
// or
return Number(a) + Number(b);

Or implicitly by using a unary + like:

return +a + +b; // to force the interpretter to interpret them as numbers

Why the other operations didn't cause the problem?

Because -, * and / are used only for numbers. So, the operands are implicitly interpretted as numbers (kind of the second solution for the addition using the unary +).

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • How does this part work in particular? I have to define op, right? and in the for loop, what does (op in operations) mean? var found = false; var op; for(op in operations) { // loop through the key of the operations object if(strings.indexOf(op) != -1) { // if strings contain that operation found = true; // then we have found one break; // stop the search } } – Giverbud Feb 05 '17 at 01:18
  • @Giverbud Are you familiar with **object**s? `for(var prop in Object)` loop through the keys of the object. In this case the object is `operations` so the keys are `add`, `substract`, `multiply` and `divide`. For all those operations we see if one of them are in the array `strings` using `**indexOf**`. – ibrahim mahrir Feb 05 '17 at 01:22
  • Nevermind I figured it out, thank you, you have helped me more than you might think! – Giverbud Feb 05 '17 at 01:25
  • sorry, one more thing, the add function you provided outputs the numbers this way: 12345 instead of 15. Instead of adding the numbers together, it lists them in a string; do you know what I could do about this? – Giverbud Feb 05 '17 at 01:31
  • @Giverbud `+` is used for both **addition** and **string concatenation**. Since those number are extracted from a dtring they're basically strings. So what you need is to implicitly or explicitly convert those strings to numbers. I'll update my answer! – ibrahim mahrir Feb 05 '17 at 01:37
  • @Giverbud see the new answer and the explanation! – ibrahim mahrir Feb 05 '17 at 01:46