isCyclc

by Sam Fereday

JavaScript 1.7

// Use this to find a node with a particular score
const findNeighbour = (query, items) => {
    return items.find(item => item.a === query || item.b === query);
}

const detectCycles = (edges) => {
    let visited = [];
    
    for(let i = 0; i < edges.length; i++) {
    
        const currentNode = edges[i];
        
        // Finds a neighbouring node with the exit value of the current node
        const cyclicNeighbour = findNeighbour(currentNode.b, visited);
        
        // Flag as visited if we've traversed it before
        visited.push({
            ...currentNode, // Spread properties (less messy)
            visited: true
        });
        
        // If we find a neighbour, and it's already visited, I believe this could indicate it's a cycle
        if (cyclicNeighbour && cyclicNeighbour.visited)
            return true;
    }
    
    return false;
}

const data = [
    {
        a: 1,
        b: 2
    },
    {
        a: 2,
        b: 3
    },
    {
        a: 3,
        b: 4
    },
    {
        a: 4,
        b: 2
    }
]

const result = detectCycles(data);
console.log(result);