repl.it
@jajoosam/

r-g-hist-chain-challenge-1

Nodejs

No description

fork
loading
Files
  • index.js
  • config.json
  • history.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const history = require("./history.json");

const len = history.length;

// chain starting from specific index
// includea the last receiver do didnt pay it forward
const findChain = (index, chain = history[index].buyer) => {
    const {buyer, receiver} = history[index];
    let longestChain = chain, payedForward = false;
    // console.log(`index: ${index} \t buyer: ${buyer} \t receiver: ${receiver} \t chain: ${longestChain}`);
    for(let i = index+1; i < len; ++i) {
        if(history[i].buyer == receiver) {
            payedForward = true;
            let c = findChain(i, chain + " -> " + receiver);
            if(c.split(" -> ").length > longestChain.split(" -> ").length) {
                longestChain = c;
            }
        }
    }
    return longestChain + (payedForward ? "" : ` -> ${receiver}`);
}

console.log(findChain(0));
?