about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--js/reshape.js35
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