How to write a helper in javascript for Multiplying arrays and strings together?

74 views Asked by At

This is just a thought experiment in me trying to learn javascript and a idea called duck typing.

function calc(a,b,c) {
    return (a+b)*c;   
}

var example1 = calc(1,2,3);
var example2 = calc([1,1,3],[2,2,3],3);
var example3 = calc ('ape ', 'and cat, ', 3)
console.log(example1, example2, example3);

How can I make the return values appear like so:

9
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
ape and cat, ape and cat, ape and cat,

Currently they will print out as:

9
NaN 
NaN

are there helpers in lo-dash?

Here's the sample code: http://repl.it/4zp/2

2

There are 2 answers

1
Calummm On BEST ANSWER

This should work with strings, numbers and arrays. Additionally, I did toy around with the idea of converting arrays to string and back again if we want to implicitly use the + operator in a similar way to strings.

function calc(a, b, c) {
    var combine, total, 
        isArray = a instanceof Array && b instanceof Array,
        i;

    combine = total = isArray ? a.concat(b) : a + b;

    for (i = 1; i < c; i++) {
        total = isArray ? total.concat(combine) : total += combine;
    }

    return total;
}
0
Suchit kumar On

it is just to show you what it suppose to do and what duck typing means.but the implementation should be done by you.it may be something like this:

function calc(a,b,c) {
     var ret=[];
 if(a.constructor === Array && b.constructor === Array){
     for(i=0;i<c;i++){
       ret=ret.concat(a.concat(b));
   }
       return ret;
     }

 if(typeof a == 'string' && typeof b == 'string'){
     var str='';
     for(i=0;i<c;i++){
         str=str+a+b;
     }
     return str;
 }

        return (a+b)*c;   
    }

    var example1 = calc(1,2,3);
    console.log(example1)
    var example2 = calc([1,1,3],[2,2,3],3);
    console.log(example2)
    var example3 = calc ('apples ', 'and oranges, ', 3)
    console.log(example3)

NOTE: you can add many more conditions to it.