K
K
Konstantin Kitmanov2013-08-15 12:06:21
JavaScript
Konstantin Kitmanov, 2013-08-15 12:06:21

[].map and String.prototype.trim

Often you have to do something like this:

function clearTags (rawTags) {
  return rawTags
    .split(',')
    .map(
      function (tag) {
        return tag.trim()
      }
    );
}


It's embarrassing that you have to write a lambda every time, and there is an intuitive feeling that you can get by with something like .map(String.prototype.trim.call)(does not work), but I did not succeed. Please share if anyone knows.

PS Solution of the form:
function clearTags (rawTags) {
  var trim = function (arg) { return String.prototype.trim.call(arg); };
  return rawTags
    .split(',')
    .map(trim);
}
trivial, not so beautiful and not without flaws.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
egorinsk, 2013-08-15
@k12th

It can be easier.
var x = string.split(/\s*,\s*/g);

A
Alexander Keith, 2013-08-15
@tenbits

The best solution, of course, is a combination of proposals from egorinsk and Aingis. I’ll add just how to get out with prototypes:

function clearTags(str){
    var trim = String.prototype.trim.call.bind(String.prototype.trim);
    return str
        .split(',')
        .map(trim);
}

But in this case it is better not to do so.

S
Sergey, 2013-08-15
Protko @Fesor

function clearTags (rawTags) {
    var trim = function (arg) { return String.prototype.trim.call(arg); };
    return rawTags
        .split(',')
        .map(trim);
}

Equivalently
function clearTags (rawTags) {
    var trim = function (tag) { return tag.trim(); };
    return rawTags
        .split(',')
        .map(trim);
}

That is, you simply assigned a closure to a variable, one more variable. No profit. Moreover, a function call was added through the prototype and through call (which itself is slower than a regular call).

O
Oleg Torbasov, 2013-08-16
@torbasow

In ECMAScript 6, writing lambdas is much easier:

str.split(",").map(function(str) str.trim());//Fx3+

or generally like this:
str.split(",").map(str=>str.trim());//Fx22+

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question