diff options
author | elioat <elioat@tilde.institute> | 2024-09-02 11:11:29 -0400 |
---|---|---|
committer | elioat <elioat@tilde.institute> | 2024-09-02 11:11:29 -0400 |
commit | ecc5db886ecbcc0aade755dc84b4b801a6314bc6 (patch) | |
tree | f47ad26186340ac1ffbdf9200bd4ed4eaa1c644d | |
parent | 84f8e346e48d267b8add0d085f87a939e72781a6 (diff) | |
download | tour-ecc5db886ecbcc0aade755dc84b4b801a6314bc6.tar.gz |
*
-rw-r--r-- | js/reshape.js | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/js/reshape.js b/js/reshape.js new file mode 100644 index 0000000..cf74f14 --- /dev/null +++ b/js/reshape.js @@ -0,0 +1,35 @@ +// more details, <https://eli.li/reshape-in-javascript-and-apl + +function ravel(array) { + if (!Array.isArray(array)) return [array]; + return array.reduce((acc, val) => acc.concat(ravel(val)), []); +} + +function reshape(shape, array) { + const totalSize = shape.reduce((acc, val) => acc * val, 1); + const ravelledArray = ravel(array); + const filledArray = []; + + for (let i = 0; i < totalSize; i++) { + filledArray.push(ravelledArray[i % ravelledArray.length]); + } + + function constructArray(shape, data, offset = 0) { + if (shape.length === 1) { + return data.slice(offset, offset + shape[0]); + } + + const size = shape[0]; + const subShape = shape.slice(1); + const subArraySize = subShape.reduce((acc, val) => acc * val, 1); + + const result = []; + for (let i = 0; i < size; i++) { + result.push(constructArray(subShape, data, offset + i * subArraySize)); + } + + return result; + } + + return constructArray(shape, filledArray); +} \ No newline at end of file |