Help to reduce Javascript code

Asked

Viewed 77 times

0

I’m making a system to leave the first letters of every minute word, but that’s not what matters. I took the first word of my name, and I turned all the letters into minuscules, and then I turned the first word into a capital letter. But I needed 2 lines for this. I wanted to know if you can join the 2 lines in one.

    <script>
        var nomePuro = "GABRIEL gUIDETti";
        var primeiroNomeMin = nomePuro.split(" ")[0];
        primeiroNomeMin = primeiroNomeMin.toLowerCase();
    </script>
  • The place for code review is in the community Code review.

  • I had it wrong? You didn’t want an algorithm on a line?

3 answers

3

It’s just deleting variables. For some reason people think they’re obligatory. They should probably learn what is a variable to then start using, then only create one when really needed. If you want in only one line:

console.log("GABRIEL gUIDETti".split(" ")[0].toLowerCase());

I also put in the Github for future reference.

This code has complexity O(N + M), but has how to make it have complexity O(N), but it is not even a requirement of the question, and anyway has a chance to be slower, even if the complexity is reduced.

1


A way to eliminate code with modern Javascript (using the technique "destructuring assignment") would be like this, only in a row:

var [primeiroNomeMin] = "GABRIEL gUIDETti".toLowerCase().split(" ");
console.log(primeiroNomeMin); // gabriel

When do we do var [primeiroNomeMin] = ... a variable with name is declared primeiroNomeMin which corresponds to the value at the first position of the array. Likewise it would be possible to save code and extract the second part of the name:

var [primeiroNome, ultimoNome] = "GABRIEL gUIDETti".toLowerCase().split(" ");
console.log(primeiroNome); // gabriel
console.log(ultimoNome); // guidetti

  • 1

    Vlw ae! That I didn’t know

0

if you want to turn it: "GABRIEL gUIDETti" in "Gabriel Guidetti"

you can do so on a single line:

console.log("GABRIEL gUIDETti".toLowerCase().replace(/\b[a-z]/g, function(letra) {
    return letra.toUpperCase();
}));

or Voce can make a function to accept any set of words and return the first of each upper case:

function primeiraUppercase(palavra){
 return palavra.toLowerCase().replace(/\b[a-z]/g, function(letra) {
    return letra.toUpperCase();
});
}

console.log(primeiraUppercase("GABRIEL gUIDETti"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.