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

69
Visualizações
How to rewrite this ramda.js code in vanilla JS

I am removing ramda from some code I've inherited as part of an effort to reduce the JavaScript size. But I'm stuck with the below because this line really baffles me as it apparently doesn't operate on any object.

var iterate = R.addIndex(R.forEach);

The relevant code looks like this:

var lis = $(el).find("ul.navbar-nav:not(.navbar-right) > li:not(.nav-more)");

var iterate = R.addIndex(R.forEach);

iterate(function(li) {
    // Other code

}, lis);

How can I write it in vanilla JS?

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

0

When R.addIndex() is applied to R.forEach() it creates a function that simply iterates over the items and for each assigns an index starting from zero:

var lis = ["a", "b", "c"];

var iterate = R.addIndex(R.forEach);

iterate(function(li, index) {
  console.log(li, index)
}, lis);
<script src="//cdn.jsdelivr.net/npm/ramda@0.25.0/dist/ramda.min.js"></script>

This is very easy to replace with vanilla JavaScript using Array.from with Array.forEach():

var lis = ["a", "b", "c"];

var iterate = (fn, list) =>
  Array.from(list)
    .forEach(fn);

iterate(function(li, index) {
  console.log(li, index);
}, lis);

In case Array.from() is not available and an ES5 solution is needed, then Array.prototype.slice() can be used to convert to array:

var lis = ["a", "b", "c"];

var iterate = function(fn, list) {
  Array.prototype.slice.call(list)
    .forEach(fn);
}

iterate(function(li, index) {
  console.log(li, index);
}, lis);

Finally, it is possible to convert to a simple for loop that works with any array-like

var lis = ["a", "b", "c"];

var iterate = function(fn, list) {
  for (var i = 0; i < list.length; i++)
    fn(list[i], i);
}

iterate(function(li, index) {
  console.log(li, index);
}, lis);

about 4 years ago · Juan Pablo Isaza Relatório

0

Convert the object to a standard array using Array.from() and then you JS Array.forEach():

const iterate = (fn, o) => Array.from(o).forEach(fn)

iterate(function(li) {
  // Other code   
}, lis);
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