I'm trying to create a function to process a list of numbers relating to depth using recursion or loops in JavaScript.
The following "input" needs to be processed into the "output", and it needs to work for arbitary lists.
One thing to note is that numbers increase by either 0 or 1 but may decrease by any amount.
var input = [0, 1, 2, 3, 1, 2, 0]
var output =
[ { number: 0, children:
[ { number: 1, children:
[ { number: 2, children:
[ { number: 3, children: [] } ]
}
]
}
, { number: 1, children:
[ { number: 2, children: [] } ]
}
]
}
, { number: 0, children: [] }
]
I worked it out myself, although it needs some refinement.
var example = [0, 1, 2, 2, 3, 1, 2, 0]
var tokens = []
var last = 0
const createJSON = (input, output) => {
if (input[0] === last) {
output.push({ num: input[0], children: [] })
createJSON(input.splice(1), output)
}
else if (input[0] > last) {
last = input[0]
output.push(createJSON(input, output[output.length-1].children))
}
else if (input[0] < last) {
var steps = input[0]
var tmp = tokens
while (steps > 0) {
tmp = tmp[tmp.length-1].children
steps--
}
tmp.push({ num: input[0], children: [] })
createJSON(input.splice(1), tmp)
}
}
createJSON(example, tokens)
console.log(tokens)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…