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

295
Visualizações
Purely functional, immutable doubly linked list in JavaScript

In JavaScript, it is trivial to create a pair of nodes that reference each other in an infinite loop:

var node = item => 
    next => 
        previous => {
            return {
                item: item,
                previous: previous,
                next: next
            };
        }; 

var z = {
    a: node('a')(() => z.b)(() => z.b),
    b: node('b')(() => z.a)(() => z.a)
};

Grab either z.a or z.b and you will be able to call next() and previous() infinitely.

Is it possible to instantiate, for instance, for a carousel with any size that can be scrolled in either direction, a circular linked list that can be of an arbitrary number of elements when it is instantiated?

I've read some things from the Haskell Wiki on "Tying the Knot", and found examples in Scala, but I'm not sure how to make these work in JavaScript.

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

0

You can use the same principle as you have used for z. Instead of creating an object with two properties a and b, create an array, which will have array indices instead.

var Node = item => 
    next => 
        previous => ({
            item: item,
            previous: previous,
            next: next
        });

var arr = (length =>
    Array.from({length}, (_, i) => 
        Node(i)(() => arr[(i + 1) % length])
               (() => arr[(i + length - 1) % length])
    )
)(4); // IIFE - we want 4 nodes in circular list

// Demo iterating the 4 nodes
var node = arr[0]; // Get one of the nodes
setInterval(() => console.log((node = node.next()).item), 500);

Recursion

Instead of storing the nodes in an array, they could be stored in recursive execution contexts.

For example:

var head = (function CircularList(previous, item, ...items) {
    if (!items.length) return { item, next: () => head, previous };
    var rest = CircularList(() => current, ...items); // Recursion
    var current = { ...rest, previous };
    return { ...rest, item, next: () => current };
})(() => head, 1, 2, 3, 4); // Example: list of four values

// Demo iterations
console.log(head.item);
for (let node = head.next(); node != head; node = node.next()) {
    console.log(node.item);
}
console.log("----");
console.log(head.item);
for (let node = head.previous(); node != head; node = node.previous()) {
    console.log(node.item);
}
console.log("----");

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