I need help with that ES6 code

Asked

Viewed 262 times

0

I’m trying to get the data that’s coming this way:

[
    {
        "name":"JONAS",
        "languages":["php","javascript","java"],
        "age":37,
        "graduate_date":1044064800000,
        "phone":"32-987-543"
    },
    {
        "name":"FLAVIO",
        "languages":["java","javascript"],
        "age":26,
        "graduate_date":1391220000000,
        "phone":"32-988-998"
    },
    {
        "name":"HENRIQUE",
        "languages":["regex","javascript","perl","go","java"],
        "age":21,
        "graduate_date":1296525600000,
        "phone":"32-888-777"
    }
] 

And turn into that:

Jonas - 26 years - 32-988-998
Flavio - 21 years - 32-888-777
Henrique - 37 years - 32-987-543
go (1)
java (3)
javascript (3)
perl (1)
php (1)
regex (1)

I’m using this code:

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

const todaydate = 1517577684000;

process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});

process.stdin.on('end',  => {
inputString = inputString
        .replace(/\s$/, '')
        .split('\n')
        .map(str => str.replace(/\s$/, '')),
main();
});

function readLine() {
return inputString[currentLine++];
}
// Complete the selectCandidates function below.
const reportCandidates = (candidatesArray) => {

//aqui ta o problema

return reportObject;
}

function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const candidates = JSON.parse(readLine());
let result = reportCandidates(candidates);

// Don't touch this code or you will die
for (let i=0; i<result.candidates.length; i++){
    ws.write(result.candidates[i].name + " - " + result.candidates[i].age +" years - " + result.candidates[i].phone +"\n");
}
for (let i=0; i<result.languages.length; i++){
    ws.write(result.languages[i].lang + " - " + result.languages[i].count +"\n");
}

ws.end();
}

Except I can’t even solve it by prayer, someone can shed some light?

  • What do you mean "they’re coming"? Coming from where? Going where? It seems to me that it comes from a command line and goes to a file, but without this information it is very difficult to specify what is the form of message exchange

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

2

I did it this way, take a look if it helps you

const meusDados = [
  {
      "name":"JONAS",
      "languages":["php","javascript","java"],
      "age":37,
      "graduate_date":1044064800000,
      "phone":"32-987-543"
  },
  {
      "name":"FLAVIO",
      "languages":["java","javascript"],
      "age":26,
      "graduate_date":1391220000000,
      "phone":"32-988-998"
  },
  {
      "name":"HENRIQUE",
      "languages":["regex","javascript","perl","go","java"],
      "age":21,
      "graduate_date":1296525600000,
      "phone":"32-888-777"
  }
] 

const exibe = (dados) => {
  let linguagens = []
  let nomeLinguagem = []
  dados.forEach(elemento => {
    console.log(`${elemento.name} - ${elemento.age} years - ${elemento.phone}`)
    elemento.languages.forEach(lang => {
      if (!linguagens[lang]) {
        linguagens[lang] = 0
        nomeLinguagem.push(lang)
      }
      linguagens[lang]++
    })
  })

  nomeLinguagem.forEach(lang => {
    console.log(`${lang} (${linguagens[lang]})`)
  })
}

exibe(meusDados)

I used the data you gave me and created a function that makes the functionality to display the data in the indicated way.

  • 2

    linguagens[lang] = 1 should be linguagens[lang] = 0

  • Well noted @Isac, thank you very much :D

0

Disregarding that you did not inform the data input and output form, I took into account that you need 3 actions:

  • Create a line with each person’s data;
  • Capitalize the first letter of each name;
  • Count the number of occurrences of each language and create a line with each one;

For the first problem, we just need to map the array original, create a array with the line destination format and use the function join of array to generate the line:

const pessoas = dados.map(({ name, age, phone }) => `${name} - ${age} years - ${phone}`);
console.log(pessoas.join(`\n`));
JONAS - 37 years - 32-987-543
FLAVIO - 26 years - 32-988-998
HENRIQUE - 21 years - 32-888-777

To turn the first letter of each word into uppercase you can use the following:

nome.split(' ')
  .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
  .join(' ');

And finally, to count the occurrences of each language, you can transform all the arrays into one and turn into one array of lines with the desired format:

const contar = (dados) => {
  const ocorrencias = {};

  // Conta as ocorrências colocando-as em um objeto
  for (const linguagem of dados) {
    ocorrencias[linguagem] = (ocorrencias[linguagem] || 0) + 1;
  }

  // Transforma o objeto com a contagem em um `array` com o formato determinado
  return Object.keys(ocorrencias).reduce((acumulador, item) => [...acumulador, `${item}(${ocorrencias[item]})`], []);
}

Putting it all together we’ll have:

// Transforma a primeira letra de cada palavra em maiúscula
const capitalizar = nome => nome.split(' ').map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase()).join(' ');

const contar = (dados) => {
  const ocorrencias = {};

  // Conta as ocorrências colocando-as em um objeto
  for (const linguagem of dados) {
    ocorrencias[linguagem] = (ocorrencias[linguagem] || 0) + 1;
  }

  // Transforma o objeto com a contagem em um `array` com o formato determinado
  return Object.keys(ocorrencias).reduce((acumulador, item) => [...acumulador, `${item}(${ocorrencias[item]})`], []);
};

const transformar = (dados) => {
  const pessoas = dados.map(({ name, age, phone }) => `${capitalizar(name)} - ${age} years - ${phone}`);
  // Transforma em um `array` de linguagens
  const linguagens = contar(dados.reduce((acumulador, { languages }) => [...acumulador, ...languages], []));
  const textoPessoas = pessoas.join('\n');
  const textoLinguagens = linguagens.join('\n');

  return `${textoPessoas}\n${textoLinguagens}`;
};

console.log(transformar([
  {
    "name":"JONAS",
    "languages":["php","javascript","java"],
    "age":37,
    "graduate_date":1044064800000,
    "phone":"32-987-543"
  },
  {
    "name":"FLAVIO",
    "languages":["java","javascript"],
    "age":26,
    "graduate_date":1391220000000,
    "phone":"32-988-998"
  },
  {
    "name":"HENRIQUE",
    "languages":["regex","javascript","perl","go","java"],
    "age":21,
    "graduate_date":1296525600000,
    "phone":"32-888-777"
  }
]));

Browser other questions tagged

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