I have an array like this:
["this", "is", ["a", ["nested", "array", "I"], "want", "to"], "split"]
And I would like a function to obtain two arrays like that:
["this", "is", ["a", ["nested", "ar"]]] [[["ray", "I"], "want", "to"], "split"]
Optimally, I would like the parameters to this function to be the initial array, the targeted string and an offset. So here, it would have been recurSplit(foo, foo[2][1][1], 2)
But I am open to any other solutions.
I made this working solution, but I am not satisfied as my hasCut variable needs to be outside the function. I'd like to know if I am on the left (or right) side of the target inside the function.
let hasCut = false
function recurSplit(element, target, offset) {
let left, right
if (typeof element == 'string') {
if (element == target) {
left = element.slice(0, offset)
right = element.slice(offset)
hasCut = true
} else {
left = hasCut ? false : element
right = hasCut ? element : false
}
} else {
left = []
right = []
for (const child of element) {
const res = recurSplit(child, target, offset)
if (res[0])
left.push(res[0])
if (res[1])
right.push(res[1])
}
}
return [left, right]
}
- Yes, I could make another function that checks it recursively, but that'd be hell of useless processing.
- Yes, I could make this function anonymous and encapsulate it inside another one, but that's very JS specific.
Isn't there any nicer ways ?
Thank you !
contextorstateparameter with default value{hasCut: false}and pass it with the recursive calls, and change that object's value instead of the variable outside the function.