94 lines
1.9 KiB
JavaScript
94 lines
1.9 KiB
JavaScript
|
var pool = require('./pool')
|
||
|
|
||
|
module.exports = {
|
||
|
shape: arrayShape,
|
||
|
flatten: flattenArray
|
||
|
}
|
||
|
|
||
|
function flatten1D (array, nx, out) {
|
||
|
for (var i = 0; i < nx; ++i) {
|
||
|
out[i] = array[i]
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function flatten2D (array, nx, ny, out) {
|
||
|
var ptr = 0
|
||
|
for (var i = 0; i < nx; ++i) {
|
||
|
var row = array[i]
|
||
|
for (var j = 0; j < ny; ++j) {
|
||
|
out[ptr++] = row[j]
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function flatten3D (array, nx, ny, nz, out, ptr_) {
|
||
|
var ptr = ptr_
|
||
|
for (var i = 0; i < nx; ++i) {
|
||
|
var row = array[i]
|
||
|
for (var j = 0; j < ny; ++j) {
|
||
|
var col = row[j]
|
||
|
for (var k = 0; k < nz; ++k) {
|
||
|
out[ptr++] = col[k]
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function flattenRec (array, shape, level, out, ptr) {
|
||
|
var stride = 1
|
||
|
for (var i = level + 1; i < shape.length; ++i) {
|
||
|
stride *= shape[i]
|
||
|
}
|
||
|
var n = shape[level]
|
||
|
if (shape.length - level === 4) {
|
||
|
var nx = shape[level + 1]
|
||
|
var ny = shape[level + 2]
|
||
|
var nz = shape[level + 3]
|
||
|
for (i = 0; i < n; ++i) {
|
||
|
flatten3D(array[i], nx, ny, nz, out, ptr)
|
||
|
ptr += stride
|
||
|
}
|
||
|
} else {
|
||
|
for (i = 0; i < n; ++i) {
|
||
|
flattenRec(array[i], shape, level + 1, out, ptr)
|
||
|
ptr += stride
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function flattenArray (array, shape, type, out_) {
|
||
|
var sz = 1
|
||
|
if (shape.length) {
|
||
|
for (var i = 0; i < shape.length; ++i) {
|
||
|
sz *= shape[i]
|
||
|
}
|
||
|
} else {
|
||
|
sz = 0
|
||
|
}
|
||
|
var out = out_ || pool.allocType(type, sz)
|
||
|
switch (shape.length) {
|
||
|
case 0:
|
||
|
break
|
||
|
case 1:
|
||
|
flatten1D(array, shape[0], out)
|
||
|
break
|
||
|
case 2:
|
||
|
flatten2D(array, shape[0], shape[1], out)
|
||
|
break
|
||
|
case 3:
|
||
|
flatten3D(array, shape[0], shape[1], shape[2], out, 0)
|
||
|
break
|
||
|
default:
|
||
|
flattenRec(array, shape, 0, out, 0)
|
||
|
}
|
||
|
return out
|
||
|
}
|
||
|
|
||
|
function arrayShape (array_) {
|
||
|
var shape = []
|
||
|
for (var array = array_; array.length; array = array[0]) {
|
||
|
shape.push(array.length)
|
||
|
}
|
||
|
return shape
|
||
|
}
|