Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ordered array #458

Merged
merged 9 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions scripts/ordered_array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* @template T
*/
export class OrderedArray {
/**
* Actual data of the array
* @type {T[]}
*/
#data = [];

/**
* Comparison function used to keep the array ordered
* @type {(e1: T, e2: T) => boolean}
*/
#fun;

/**
* @param {(e1: T, e2: T) => boolean} fun
*/
constructor(fun) {
this.#fun = fun;
}

/**
* insert an element in the array.
* @param{T} x
*/
insert(x) {
// TODO: optimize with binary search so that running time is O(log(N)) instead of O(N)
for (const [i, el] of this.#data.entries()) {
if (this.#fun(x, el)) {
this.#data.splice(i, 0, x);
return;
}
}
this.#data.push(x);
}

/**
* Remove the first element that satisfies the condition cond
* @param {(e1: T) => boolean} cond
*/
remove(cond) {
for (const [i, el] of this.#data.entries()) {
if (cond(el)) {
this.#data.splice(i, 1);
return;
}
}
}

/**
* @returns {T[]}
*/
get() {
return this.#data;
}

clear() {
this.#data = [];
}
}
5 changes: 4 additions & 1 deletion scripts/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ export class Transaction {
blockTime;
/** @type{number} */
lockTime;
/** Cached txid */
/**
* Cached txid
* @type {string}
*/
#txid = '';

constructor({
Expand Down
2 changes: 1 addition & 1 deletion scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export function sleep(ms) {
* @param {number} N
* @returns {number}
*/
function getRandomInt(N) {
export function getRandomInt(N) {
return Math.floor(Math.random() * N);
}

Expand Down
36 changes: 15 additions & 21 deletions scripts/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { TransactionBuilder } from './transaction_builder.js';
import { createAlert } from './alerts/alert.js';
import { AsyncInterval } from './async_interval.js';
import { debugError, DebugTopics } from './debug.js';
import { OrderedArray } from './ordered_array.js';

/**
* Class Wallet, at the moment it is just a "realization" of Masterkey with a given nAccount
Expand Down Expand Up @@ -101,9 +102,11 @@ export class Wallet {
#lastProcessedBlock = 0;
/**
* Array of historical txs, ordered by block height
* @type HistoricalTx[]
* @type OrderedArray<HistoricalTx>
*/
#historicalTxs;
#historicalTxs = new OrderedArray(
(hTx1, hTx2) => hTx1.blockHeight >= hTx2.blockHeight
);

constructor({ nAccount, masterKey, shield, mempool = new Mempool() }) {
this.#nAccount = nAccount;
Expand Down Expand Up @@ -253,7 +256,7 @@ export class Wallet {
}
this.#mempool = new Mempool();
this.#lastProcessedBlock = 0;
this.#historicalTxs = [];
this.#historicalTxs.clear();
}

/**
Expand Down Expand Up @@ -698,26 +701,15 @@ export class Wallet {
* @param {Transaction} tx
*/
#pushToHistoricalTx(tx) {
const historicalTx = this.toHistoricalTXs([tx])[0];
let prevHeight = Number.POSITIVE_INFINITY;
for (const [i, hTx] of this.#historicalTxs.entries()) {
if (
historicalTx.blockHeight <= prevHeight &&
historicalTx.blockHeight >= hTx.blockHeight
) {
this.#historicalTxs.splice(i, 0, historicalTx);
return;
}
prevHeight = hTx.blockHeight;
}
this.#historicalTxs.push(historicalTx);
const hTx = this.toHistoricalTXs([tx])[0];
this.#historicalTxs.insert(hTx);
}

/**
* @returns {HistoricalTx[]}
*/
getHistoricalTxs() {
return this.#historicalTxs;
return this.#historicalTxs.get();
}
sync = lockableFunction(async () => {
if (this.#isSynced) {
Expand Down Expand Up @@ -1211,10 +1203,12 @@ export class Wallet {
const db = await Database.getInstance();
await db.storeTx(transaction);
}
if (!tx || tx.blockHeight === -1) {
// Do not add unconfirmed txs to history
if (transaction.blockHeight !== -1)
this.#pushToHistoricalTx(transaction);

if (tx && tx.blockHeight !== -1) {
this.#historicalTxs.remove((hTx) => hTx.id === tx.txid);
this.#pushToHistoricalTx(transaction);
} else if (transaction.blockHeight !== -1) {
this.#pushToHistoricalTx(transaction);
}
}

Expand Down
54 changes: 54 additions & 0 deletions tests/unit/ordered_array.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { OrderedArray } from '../../scripts/ordered_array.js';
import { beforeEach, it } from 'vitest';
import { getRandomInt } from '../../scripts/utils.js';

function verifyOrder(arr, fn) {
let prev = arr[0];
for (let i = 1; i < arr.length; i++) {
expect(fn(prev, arr[i]));
prev = arr[i];
}
}
function insertFirstNaturals(arr, N) {
for (let i = 0; i < N; i++) {
arr.insert(i);
}
}
describe('Ordered array tests', () => {
/**
* @type OrderedArray<number>
*/
let arr;
const sleep_time = 1000;
beforeEach(() => {
arr = new OrderedArray((x, y) => x >= y);
});
it('is actually ordered', () => {
const Nit = 100;
const Max = 1000;
for (let i = 0; i < Nit; i++) {
arr.insert(getRandomInt(Max));
}
verifyOrder(arr);
});
it('returns the internal data correctly', () => {
insertFirstNaturals(arr, 3);
expect(arr.get()).toStrictEqual([2, 1, 0]);
});
it('deletes correctly', () => {
insertFirstNaturals(arr, 6);
expect(arr.get()).toStrictEqual([5, 4, 3, 2, 1, 0]);
arr.remove((x) => x === 1);
expect(arr.get()).toStrictEqual([5, 4, 3, 2, 0]);
arr.remove((x) => x < 4);
expect(arr.get()).toStrictEqual([5, 4, 2, 0]);
arr.remove((x) => x > 5);
expect(arr.get()).toStrictEqual([5, 4, 2, 0]);
});
it('clears correctly', () => {
insertFirstNaturals(arr, 6);
expect(arr.get()).toStrictEqual([5, 4, 3, 2, 1, 0]);
arr.clear();
expect(arr.get()).toStrictEqual([]);
});
});
Loading