arnaucube
arnaucube/circomPublic Self-hosted repository
circom/src/stream_from_multiarray.js
src/stream_from_multiarray.jsRaw
 1
 2const Readable = require("stream").Readable;
 3
 4module.exports = function streamFromMultiarray(ma) {
 5    const  rs = Readable();
 6
 7    let curIndex = getFirstIdx(ma);
 8
 9    rs._read = function() {
10        let res;
11        do {
12            res = objFromIdx(ma, curIndex);
13            curIndex = nextIdx(curIndex);
14        } while (res==="");
15        rs.push(res);
16    };
17
18
19    return rs;
20
21
22    function getFirstIdx(ma) {
23        if (!Array.isArray(ma)) return [];
24        return [0, ...getFirstIdx(ma[0])];
25    }
26
27    function nextIdx(idx) {
28        if (idx == null) return null;
29        if (idx.length == 0) return null;
30
31        const parentIdx = idx.slice(0,-1);
32
33        const itObj = objFromIdx(ma, parentIdx);
34        const newLastIdx = idx[idx.length-1]+1;
35        if (newLastIdx < itObj.length) {
36            const resIdx = idx.slice();
37            resIdx[resIdx.length-1] = newLastIdx;
38            return [...resIdx, ...getFirstIdx(itObj[newLastIdx])];
39        } else {
40            return nextIdx(parentIdx);
41        }
42    }
43
44    function objFromIdx(ma, idx) {
45        if (idx == null) return null;
46        if (idx.length == 0) return ma;
47        if (ma.length == 0) return "";
48        return objFromIdx(ma[idx[0]], idx.slice(1));
49    }
50};