upend/tools/upend_js/index.ts

77 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-12-18 15:12:22 +01:00
import type {
Address,
IEntry,
ListingResult,
OrderedListing,
VALUE_TYPE,
} from "./types";
2021-11-11 23:37:42 +01:00
export function listingAsOrdered(listing: ListingResult): OrderedListing {
const entries = Object.entries(listing) as [Address, IEntry][];
return entries
2021-12-18 15:12:22 +01:00
.sort(([_, a], [__, b]) =>
String(a.value.c).localeCompare(String(b.value.c))
)
.sort(([_, a], [__, b]) =>
String(a.value.t).localeCompare(String(b.value.t))
)
2021-11-11 23:37:42 +01:00
.sort(([_, a], [__, b]) => a.attribute.localeCompare(b.attribute));
}
2021-12-18 15:12:22 +01:00
export class UpListing {
private entries: UpEntry[];
constructor(listing: ListingResult) {
this.entries = Object.entries(listing).map((lr) => new UpEntry(...lr));
}
public get objects(): UpObject[] {
const allEntities = new Set(this.entries.map((e) => e.entity));
return Array.from(allEntities).map((entity) => new UpObject(entity));
}
}
export class UpObject {
public readonly address;
constructor(address: string) {
this.address = address;
}
public attr(entries: UpEntry[]) {
const result = {} as { [key: string]: UpEntry[] };
entries
.filter((e) => e.entity == this.address)
.forEach((entry) => {
if (!result[entry.attribute]) {
result[entry.attribute] = [];
}
result[entry.attribute].push(entry);
});
return result;
}
public asDict(entries: UpEntry[]) {
return {
address: this.address,
attributes: this.attr(entries),
};
}
}
export class UpEntry extends UpObject implements IEntry {
entity: string;
attribute: string;
value: { t: VALUE_TYPE; c: string | number };
constructor(address: string, entry: IEntry) {
super(address);
this.entity = entry.entity;
this.attribute = entry.attribute;
this.value = entry.value;
}
2021-11-11 23:37:42 +01:00
}