Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
Is there better way than write match very much?

HI, i have this code

let key = N001DSC29MC22HC22DD04MD09YD21
function get(key) {
  let res = {};
  res.matchNumber = key.match(/(?<=N)\d{3}/g);
  res.matchSeconds = key.match(/(?<=DSC)\d{2}/g);
  res.matchMinutes = key.match(/(?<=MC)\d{2}/g);
  res.matchHours = key.match(/(?<=HC)\d{2}/g);
  res.matchDay = key.match(/(?<=DD)\d{2}/g);
  res.matchMonth = key.match(/(?<=MD)\d{2}/g);
  res.matchYear = key.match(/(?<=YD)\d{2}/g);
  res.title = JSON.parse(localStorage.getItem(key)).title;
  res.description = JSON.parse(localStorage.getItem(key)).description;
  Object.keys(res).forEach(key => {
    if (! res[key]) delete res[key]
    if (Array.isArray(res[key])) res[key] = res[key].join('')
  })
  return res;
}
get(key)

As you can see my code not clean, there is any better way to do the same function. I really try and i can't do better

I Mean there is better from using REGEXP And match very mush Like this

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In my opinion, you can put the initialization of the object fields inline with the creation of the object, and foreach is not the best to do side effect, try to make object const and use something like filter and reduce:

// the snipped won't work because of the sandbox policy
let key = 'N001DSC29MC22HC22DD04MD09YD21';
function get(key) {
  const res = {
    matchNumber : key.match(/(?<=N)\d{3}/g),
    matchSeconds : key.match(/(?<=DSC)\d{2}/g),
    matchMinutes : key.match(/(?<=MC)\d{2}/g),
    matchHours : key.match(/(?<=HC)\d{2}/g),
    matchDay : key.match(/(?<=DD)\d{2}/g),
    matchMonth : key.match(/(?<=MD)\d{2}/g),
    matchYear : key.match(/(?<=YD)\d{2}/g),
    title : JSON.parse(localStorage.getItem(key)).title,
    description : JSON.parse(localStorage.getItem(key)).description,
  };
  return Object.entries(res)
    .filter(([k]) => k)
    .reduce((acc, [k,v]) => (acc[k] = v, acc), {})
}
get(key)

However, you can actually just avoid creating the res object and start with another data structure (the one that Object.entries will return)

let key = 'N001DSC29MC22HC22DD04MD09YD21';
function get(key) {
  return [
    ['matchNumber' , key.match(/(?<=N)\d{3}/g)],
    ['matchSeconds' , key.match(/(?<=DSC)\d{2}/g)],
    ['matchMinutes' , key.match(/(?<=MC)\d{2}/g)],
    ['matchHours' , key.match(/(?<=HC)\d{2}/g)],
    ['matchDay' , key.match(/(?<=DD)\d{2}/g)],
    ['matchMonth' , key.match(/(?<=MD)\d{2}/g)],
    ['matchYear' , key.match(/(?<=YD)\d{2}/g)],
    ['title' , JSON.parse(localStorage.getItem(key)).title],
    ['description' , JSON.parse(localStorage.getItem(key)).description],
  ].filter(([k]) => k).reduce((acc, [k,v]) => (acc[k] = v, acc), {})
}
get(key)

about 4 years ago · Juan Pablo Isaza Relatório

0

Creating an Object using Object.fromEntries, where entries are filtered and mapped from Object.entries looks a bit cleaner.

console.log(get(`N001DSC29MC22HC22DD04MD09YD21`));

function get(key) {
 return Object.fromEntries(
  Object.entries({
      matchNumber: key.match(/(?<=N)\d{3}/g),
      matchSeconds: key.match(/(?<=DSC)\d{2}/g),
      matchMinutes: key.match(/(?<=MC)\d{2}/g),
      matchHours: key.match(/(?<=HC)\d{2}/g),
      matchDay: key.match(/(?<=DD)\d{2}/g),
      matchMonth: key.match(/(?<=MD)\d{2}/g),
      matchYear: key.match(/(?<=YD)\d{2}/g),
      // mockup for not working localStorage in sandbox   
      title: `sometitle`,
      description: `somedescription`,
    })
    // filter only key-value pairs with a value
    .filter( ([key, value]) => value )
    // map to values with joined Arrays if applic.
    .map( ([key, value]) => 
      [key, Array.isArray(value) ? value.join('') : value ] )
  );
}

Alternative, labels and regexes from one raw string, using one reducer to create the object.

const getValuesFromKey = key => ({ 
    ...String.raw`
      ID::(?<=N)\d{3}
      Seconds::(?<=DSC)\d{2}
      Minutes::(?<=MC)\d{2}
      Hours::(?<=HC)\d{2}
      Day::(?<=DD)\d{2}
      Month::(?<=MD)\d{2}
      NoMatch::(?<=NOTHING)\d{2} // won't match anything
      Years::(?<=YD)\d{2} // will find two years `
    .split(`\n`)
    .reduce( (acc, line) => {
      line = line.replace(/\/\/.*$/, ``).trim();
      const [label, re] = line && line.split(`::`);
      const match = re && key.match(new RegExp(re, `g`));
      return match ? {...acc, [[label]]: match.join(` and `)} : acc;
    }, {}),
    Title: `someTitle`,
    Description: `someDescription` });

console.log(getValuesFromKey(`N001DSC29MC22HC22DD04MD09YD21YD45`));
//                                                         ^ extra value

Or use named capture groups. See this stackblitz project

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda