forked from orbs-network/single-nominator
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.ts
88 lines (71 loc) · 2.34 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { Tuple, TupleItem, TupleReader } from "@ton/core";
export const buff2bigint = (buff: Buffer) : bigint => {
return BigInt("0x" + buff.toString("hex"));
}
export const bigint2buff = (num:bigint) : Buffer => {
let buffStr = num.toString(16);
if(buffStr.length % 2 != 0) {
buffStr = "0" + buffStr;
}
return Buffer.from(buffStr, 'hex')
}
const getRandom = (min:number, max:number) => {
return Math.random() * (max - min) + min;
}
export const getRandomInt = (min: number, max: number) => {
return Math.round(getRandom(min, max));
}
interface IAny {}
interface TupleReaderConstructor <T extends IAny>{
new (...args: any[]) : T
fromReader(rdr: TupleReader) : T;
}
class TupleReaderFactory<T extends IAny>{
private constructable: TupleReaderConstructor<T>;
constructor(constructable: TupleReaderConstructor<T>) {
this.constructable = constructable;
}
createObject(rdr: TupleReader) : T {
return this.constructable.fromReader(rdr);
}
}
class LispIterator <T extends IAny> implements Iterator <T> {
private curItem:TupleReader | null;
private done:boolean;
private ctor: TupleReaderFactory<T>;
constructor(tuple:TupleReader | null, ctor: TupleReaderFactory<T>) {
this.done = false; //tuple === null || tuple.remaining == 0;
this.curItem = tuple;
this.ctor = ctor;
}
public next(): IteratorResult<T> {
this.done = this.curItem === null || this.curItem.remaining == 0;
let value: TupleReader;
if( ! this.done) {
const head = this.curItem!.readTuple();
const tail = this.curItem!.readTupleOpt();
if(tail !== null) {
this.curItem = tail;
}
value = head;
return {done: this.done, value: this.ctor.createObject(value)};
}
else {
return {done: true, value: null}
}
}
}
export class LispList <T extends IAny> {
private tuple: TupleReader | null;
private ctor: TupleReaderFactory<T>;
constructor(tuple: TupleReader | null, ctor: TupleReaderConstructor<T>) {
this.tuple = tuple;
this.ctor = new TupleReaderFactory(ctor);
}
toArray() : T[] {
return [...this];
}
[Symbol.iterator]() {
return new LispIterator(this.tuple, this.ctor);
}
}