So currently I have this function:
function loadPath(chunkSize, dataSize, depth, index) {
let path = []
let i = 0
while (i < depth) {
path.unshift(index % chunkSize)
index = Math.floor(index / chunkSize)
i++
}
return path
}
I would now like to pass in path
as a variable from an object pool of short path arrays. So for example:
function loadPath(path, chunkSize, dataSize, depth, index) {
}
let path = new Array(3)
loadPath(path, 5, 100, 3, 41)
console.log(path) // 1, 3, 1
loadPath(path, 5, 100, 3, 50)
console.log(path) // ...
The question is, how can I do that without using push/unshift or reverse operations on the array? Basically just treating the array as a static block of memory, while at the same time not adding any unnecessary operations.
function loadPath(path, chunkSize, dataSize, depth, index) {
let i = 0
let x = depth - 1
while (i < depth) {
path[x] = index % chunkSize
index = Math.floor(index / chunkSize)
i++
x--
}
}
My question is, can this be done with any fewer temp variables? Some magic along the lines of this?
function loadPath(path, chunkSize, dataSize, depth, index) {
let i = 0
while (i < depth) {
// something tricky perhaps here?
// since x and i have a reciprocal relationship...
// somehow fill it in backwards...
path[depth - i] = index % chunkSize
index = Math.floor(index / chunkSize)
i++
}
}
Or perhaps there is another way entirely to write this algorithm to be in as few steps and operations and temp variables as possible.
Could also use this floor
implementation integrated somehow if it helps :)
function floor(n) {
return ~~n - (~~n > n)
}
Math.log(chunkSize) / Math.log(index)
(rounded up). \$\endgroup\$concat
? \$\endgroup\$path[depth - i - 1] = index % chunkSize
- no need forx
. \$\endgroup\$index
and what is/why are you not usingdataSize
? \$\endgroup\$