arnaucube
arnaucube/circomPublic Self-hosted repository
circom/src/bigarray.js
src/bigarray.jsRaw
 1const SUBARRAY_SIZE = 0x40000;
 2
 3const BigArrayHandler = {
 4    get: function(obj, prop) {
 5        if (!isNaN(prop)) {
 6            return obj.getElement(prop);
 7        } else return obj[prop];
 8    },
 9    set: function(obj, prop, value) {
10        if (!isNaN(prop)) {
11            return obj.setElement(prop, value);
12        } else {
13            obj[prop] = value;
14            return true;
15        }
16    }
17};
18
19class _BigArray {
20    constructor (initSize) {
21        this.length = initSize || 0;
22        this.arr = new Array(SUBARRAY_SIZE);
23
24        for (let i=0; i<initSize; i+=SUBARRAY_SIZE) {
25            this.arr[i/SUBARRAY_SIZE] = new Array(Math.min(SUBARRAY_SIZE, initSize - i));
26        }
27        return this;
28    }
29    push (element) {
30        this.setElement (this.length, element);
31    }
32    getElement(idx) {
33        idx = parseInt(idx);
34        const idx1 = Math.floor(idx / SUBARRAY_SIZE);
35        const idx2 = idx % SUBARRAY_SIZE;
36        return this.arr[idx1] ? this.arr[idx1][idx2] : undefined;
37    }
38    setElement(idx, value) {
39        idx = parseInt(idx);
40        const idx1 = Math.floor(idx / SUBARRAY_SIZE);
41        if (!this.arr[idx1]) {
42            this.arr[idx1] = new Array(SUBARRAY_SIZE);
43        }
44        const idx2 = idx % SUBARRAY_SIZE;
45        this.arr[idx1][idx2] = value;
46        if (idx >= this.length) this.length = idx+1;
47        return true;
48    }
49    getKeys() {
50        const newA = new BigArray();
51        for (let i=0; i<this.arr.length; i++) {
52            if (this.arr[i]) {
53                for (let j=0; j<this.arr[i].length; j++) {
54                    if (typeof this.arr[i][j] !== "undefined") {
55                        newA.push(i*SUBARRAY_SIZE+j);
56                    }
57                }
58            }
59        }
60        return newA;
61    }
62}
63
64class BigArray {
65    constructor( initSize ) {
66        const obj = new _BigArray(initSize);
67        const extObj = new Proxy(obj, BigArrayHandler);
68        return extObj;
69    }
70}
71
72module.exports = BigArray;