Forget about concat and start using concat

May 18, 2020 • edited May 19, 2020

It may sound crazy but Array.prototype.concat()from javascript I think it is the worst implementation that we can find in any modern language to concatenate variables or portions of texts to another text string.

We can concatenate in two ways:

var mensaje = "Buenos días, ";
var nombre = "Junior";
console.log( mensaje.concat(nombre) );
// RESPUESTA: "Buenos días, Junior"

var mensaje = "Buenos días, ";
var nombre = "Junior";
console.log( mensaje + nombre );
// RESPUESTA: "Buenos días, Junior"

Don’t they look good? Doesn’t the second look more comfortable than the first? Try using either method with a long text string to see if you think the same.

It is very rare to see javascript programmers use concat(), instead they prefer +, much simpler to apply. Both can work for short strings, but if we embed several lines of HTML in our code as a template, it becomes hell.

How about we extend concat()and make it look like formatPython to make it more usable? Let’s see the script:

String.prototype.concat = function ()
{
    var arg = arguments || [];
    var str = String(this).split('%s') || [];

    for ( var i = 0, c = str.length, f = []; i < c; i++ )
    {
        f.push( str[i] + (arg[i] ? arg[i] : '') );
    };

    return f.join('');
};

Let’s see how to use it:

var texto = "Es un %s. Cosas extrañas nos esperan en los %s. %s, no lo sé, pero nos llaman.";

var porcion1 = 'amanecer rojo';
var porcion2 = 'lindes del bosque';
var porcion3 = 'Buenas o malas';

console.log( texto.concat(porcion1, porcion2, porcion3) );
// RESPUESTA: "Es un amanecer rojo. Cosas extrañas nos esperan en los lindes del bosque. Buenas o malas, no lo sé, pero nos llaman."

The script tries to locate all the inputs with the symbol %sand replace them with the variables in the same order that they were added in the arguments.

Now (with a little cheating) we can say that it concat()is the best alternative to concatenate portions of text to long strings. Then we leave a +for short chains.

I challenge someone to improve it. ;-)

JavaScript

Junihh

Junihh is talk about web-dev and opinion.

Filter json data from a key

New scheme for a more semantic web