2

No jQuery please!

The Web says that the native String.concat() and join() functions of JS are to be avoided because of their poor performance, and a simple for() loop of += assignments should work a lot faster.

So I'm trying to create a function in pure JavaScript that will concatenate strings. This is somewhat how I envision it:

  • I want a main function concatenate() that will concatenate all passed arguments and additionally insert a variable string after each concatenated argument, except for the last one.

  • If the main function is called by itself and without the chained .using() function, then that variable string should be an empty one, which means no separators in the result.

  • I want a chained sub-function .using() that will tell the main concatenate() function what certain string other than the default '' empty string to add after each concatenated segment.

In theory, it should work like this:

concatenate('a','b','c');              /* result: 'abc'   */
concatenate('a','b','c').using('-');   /* result: 'a-b-c' */

I want to avoid having two separate functions, like concatenate() and concatenateUsing(), because the concatenateUsing() variant would then have to utilize a special constant argument (like arguments[0] or arguments[arguments.length-1]) as the injected separator and that would be terribly untidy. Plus, I would always forget which one it was.

I also want to avoid having a superceding Concatenate object with two separate sub-methods, like Concatenate.strings() and Concatenate.using() or similar.

Here are some of my failed attempts so far...

Attempt #1:

function concatenate()
{
  var result="";
  if(this.separator===undefined){var separator=false;}

  for(var i=0; i<arguments.length; i++)
  {result += arguments[i] + ((separator && (i<arguments.length-1))?separator:'');}

  this.using=function(x)
  {
    this.separator=x;
    return this;
  }

  return result;
}

So what I'm trying to do is:

  • check if the separator variable is undefined, this means it wasn't set from a sub-method yet.

  • If it's undefined, declare it with the value false for later evaluation.

  • Run the concatenation, and if separator has another value than false then use it in each concatenation step - as long as it's not the last iteration.

  • Then return the result.

  • The sub-method .using(x) should somewhere along the way set the value of the separator variable.

Naturally, this doesn't work.

Attempt #2:

var concatenate = function()
{
  var result="";
  var separator="";
  for(var i=0; i<arguments.length; i++)
    {result += arguments[i] + ((separator && (i<arguments.length-1))?separator:'');}
  return result;
}

concatenate.prototype.using=function(x)
{
  this.separator=x;
  return this;
}

It also doesn't work, I assume that when this is returned from the using() sub-method, the var separator="" of the main concatenate() function just overwrites the value with "" again.

I tried doing this 4 or 5 different ways now, but I don't want to bore you with all the others as well.

Does anyone know a solution for this puzzle? Thanks a lot in advance!

3
  • 1
    The web says a lot things, and many of them are wrong or outdated. Please link the claims you found.
    – Bergi
    Jun 3, 2015 at 16:37
  • Yeah, using the + operator is recommended over a .concat() call (with all its overhead) if you need to concat two string values. Yet that doesn't say anything about join, and it depends a lot on where your values are coming from (variables? literals? array items?). That jsperf you linked as a "proof" is flawed, this would be a better comparison (although it's still a microbenchmark and suffers from overoptimisations in various engines)
    – Bergi
    Jun 3, 2015 at 17:33

1 Answer 1

5

What you are trying to do is impossible.

You cannot chain something to a method call that returns a primitive, because primitives do not have (custom) methods1.
And you cannot make the first function return different things depending on whether something is chained or not, because it doesn't know about its call context and has to return the result before the method call is evaluated.

Your best bet is to return an object that can be stringified using a custom toString method, and also offers that using thing. It would be something along the lines of

function concatenate() {
    return {
        args: Array.from(arguments), // ES6 for simplicity
        using: function(separator) {
            return this.args.join(separator);
        },
        toString: function() {
            return this.args.join("");
        }
    };
}

console.log(String(concatenate('a','b','c'))); // result: 'abc'
// alternatively, use ""+… or explicitly call the ….toString() method
console.log(concatenate('a','b','c').using('-')); // result: 'a-b-c'

1: No, you don't want to know workarounds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.