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

Array functions (concat, pluck) #46

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
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
Prev Previous commit
Implements ArrayPluck Directive, and FutureArray.pluck
  • Loading branch information
liamgriffiths committed Apr 3, 2024
commit a4115e577b7cca44c3d5db2cc9b6f39c02b2c63a
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

120 changes: 107 additions & 13 deletions src/Future.ts
Original file line number Diff line number Diff line change
@@ -2,13 +2,13 @@ import { idGenerator } from "substrate/idGenerator";
import { Node } from "substrate/Node";

type Accessor = "item" | "attr";
type TraceOperation = {
type Operation = {
future_id: string | null;
key: string | number | null;
accessor: Accessor;
};

type TraceProp = string | FutureString | number | FutureNumber;
type PathProp = string | FutureString | number | FutureNumber;
type StringConcatable = string | FutureString;
type ArrayConcatable =
| string
@@ -18,7 +18,7 @@ type ArrayConcatable =
| Future
| Future[];

const parsePath = (path: string): TraceProp[] => {
const parsePath = (path: string): PathProp[] => {
// Split the path by dots or brackets, and filter out empty strings
const parts = path.split(/\.|\[|\]\[?/).filter(Boolean);
// Convert numeric parts to numbers and keep others as strings
@@ -27,13 +27,22 @@ const parsePath = (path: string): TraceProp[] => {

const newFutureId = idGenerator("future");

/** @private */
abstract class Directive {
/** A directive contains a set of values or instructions */
abstract items: any[];

/** Produces a new `Directive` with provided args from an existing `Directive` */
// NOTE: also open to changing the name of this function, just not sure what to name it yet (eg. `extend`, `with`)
abstract next(...args: any[]): Directive;

/** Transforms the `Directive` into JSON */
abstract toJSON(): any;

/** Returns the eventual resulting value from the `Directive` */
abstract result(): Promise<any>;

/** Returns all referenced `Future` instances (recursive) present in instance's `items` */
referencedFutures() {
// @ts-ignore
return this.items
@@ -42,11 +51,12 @@ abstract class Directive {
}
}

/** @private */
export class Trace extends Directive {
items: TraceProp[];
items: PathProp[];
originNode: Node<any>;

constructor(items: TraceProp[], originNode: Node<any>) {
constructor(items: PathProp[], originNode: Node<any>) {
super();
this.items = items;
this.originNode = originNode;
@@ -65,7 +75,7 @@ export class Trace extends Directive {
}),
};

override next(...items: TraceProp[]) {
override next(...items: PathProp[]) {
return new Trace([...this.items, ...items], this.originNode);
}

@@ -96,11 +106,12 @@ export class Trace extends Directive {
return Trace.Operation.key("attr", item);
}
return Trace.Operation.key("item", item);
}) as TraceOperation[],
}) as Operation[],
};
}
}

/** @private */
export class StringConcat extends Directive {
items: StringConcatable[];

@@ -109,7 +120,7 @@ export class StringConcat extends Directive {
this.items = items;
}

static Concatable = {
static Item = {
string: (val: string) => ({ future_id: null, val }),
future: (id: Future["id"]) => ({ future_id: id, val: null }),
};
@@ -135,14 +146,15 @@ export class StringConcat extends Directive {
items: this.items.map((item) => {
if (item instanceof Future) {
// @ts-expect-error (accessing protected prop: id)
return StringConcat.Concatable.future(item.id);
return StringConcat.Item.future(item.id);
}
return StringConcat.Concatable.string(item);
return StringConcat.Item.string(item);
}),
};
}
}

/** @private */
export class ArrayConcat extends Directive {
items: ArrayConcatable[];

@@ -151,7 +163,7 @@ export class ArrayConcat extends Directive {
this.items = items;
}

static Concatable = {
static Item = {
static: (val: string | number | number[] | string[]) => ({
future_id: null,
val,
@@ -180,16 +192,86 @@ export class ArrayConcat extends Directive {
items: this.items.map((item) => {
if (item instanceof Future) {
// @ts-expect-error (accessing protected prop: id)
return ArrayConcat.Concatable.future(item.id);
return ArrayConcat.Item.future(item.id);
}
return ArrayConcat.Concatable.static(
return ArrayConcat.Item.static(
item as string | number | string[] | number[],
);
}),
};
}
}

/** @private */
export class ArrayPluck extends Directive {
items: PathProp[];
target: FutureArray;

constructor(items: PathProp[] = [], target: FutureArray) {
super();
this.items = items;
this.target = target;
}

static Operation = {
future: (accessor: Accessor, id: Future["id"]) => ({
future_id: id,
key: null,
accessor,
}),
key: (accessor: Accessor, key: string | number) => ({
future_id: null,
key,
accessor,
}),
};

override next(...items: PathProp[]): ArrayConcat {
return new ArrayPluck([...this.items, ...items], this.target);
}

override async result(): Promise<any[]> {
// resolve the value of the target future
let result: any[] = await this.target.result();

// resolve all the path properties
const path = await Promise.all(
this.items.map((item) => (item instanceof Future ? item.result() : item)),
);

// then for each item in the results, select the value at the given path
return result.map((item) => {
let obj = item;
for (let p of path) obj = obj[p];
return obj;
});
}

override referencedFutures() {
return [this.target, ...super.referencedFutures()];
}

override toJSON() {
return {
type: "array-pluck",
// @ts-expect-error (accessing protected prop: id)
target_future_id: this.target.id,
op_stack: this.items.map((item) => {
if (item instanceof FutureString) {
// @ts-expect-error (accessing protected prop: id)
return ArrayPluck.Operation.future("attr", item.id);
} else if (item instanceof FutureNumber) {
// @ts-expect-error (accessing protected prop: id)
return ArrayPluck.Operation.future("item", item.id);
} else if (typeof item === "string") {
return ArrayPluck.Operation.key("attr", item);
}
return ArrayPluck.Operation.key("item", item);
}) as Operation[],
};
}
}

export abstract class Future {
protected directive: Directive;
protected id: string = "";
@@ -268,6 +350,18 @@ export class FutureArray extends Future {
return FutureArray.concat(...[this as FutureArray, ...items]);
}

static pluck(props: PathProp[], target: FutureArray) {
const items =
props.length === 1 && typeof props.at(0) === "string"
? parsePath(props.at(0) as string)
: props;
return new FutureArray(new ArrayPluck(items, target));
}

pluck(...props: PathProp[]) {
return FutureArray.pluck(props, this);
}

override async result(): Promise<any[]> {
return super.result() as Promise<any[]>;
}
99 changes: 90 additions & 9 deletions tests/Future.test.ts
Original file line number Diff line number Diff line change
@@ -9,12 +9,13 @@ import {
Trace,
StringConcat,
ArrayConcat,
ArrayPluck,
} from "substrate/Future";
import { Node } from "substrate/Node";
import { SubstrateResponse } from "substrate/SubstrateResponse";
import { RequestCompleted } from "substrate/Mailbox";

class FooFuture extends Future {}
class FooFuture extends Future { }

const node = (id: string = "") => new Node({}, { id });

@@ -144,10 +145,7 @@ describe("Future", () => {

expect(d.toJSON()).toEqual({
type: "string-concat",
items: [
StringConcat.Concatable.string("a"),
StringConcat.Concatable.future("123"),
],
items: [StringConcat.Item.string("a"), StringConcat.Item.future("123")],
});
});

@@ -195,10 +193,10 @@ describe("Future", () => {
expect(a.toJSON()).toEqual({
type: "array-concat",
items: [
ArrayConcat.Concatable.static(["a"]),
ArrayConcat.Concatable.static("b"),
ArrayConcat.Concatable.future("FutureStringId"),
ArrayConcat.Concatable.future("FutureArrayId"),
ArrayConcat.Item.static(["a"]),
ArrayConcat.Item.static("b"),
ArrayConcat.Item.future("FutureStringId"),
ArrayConcat.Item.future("FutureArrayId"),
],
});
});
@@ -215,6 +213,65 @@ describe("Future", () => {
});
});

describe("ArrayPluck (Directive)", () => {
test(".next", () => {
const fa = new TestFutureArray(new Trace([], node()));
const fs = new FutureString(new Trace([], node()));
const d = new ArrayPluck(["a", "b"], fa);
const d2 = d.next(fs);

expect(d2.items).toEqual(["a", "b", fs]);
});

test(".result", async () => {
const arr = new TestFutureArray(
new Trace([], staticNode([{ a: [1] }, { a: [2] }])),
);

// when the items are empty (it selects value at root path for each)
const a0 = new ArrayPluck([], arr);
expect(a0.result()).resolves.toEqual([{ a: [1] }, { a: [2] }]);

// when the items only includes primitive values
const a1 = new ArrayPluck(["a", 0], arr);
expect(a1.result()).resolves.toEqual([1, 2]);

// when the items includes futures
const fs = new FutureString(new Trace([], staticNode("a")));
const a2 = new ArrayPluck([fs, 0], arr);
expect(a2.result()).resolves.toEqual([1, 2]);
});

test(".toJSON", () => {
const arr = new TestFutureArray(
new Trace([], staticNode([{ a: { b: [1] } }])), "FutureArrayId"
);

const fs = new FutureString(new Trace([], staticNode("a")), "FutureStringId");
const a = new ArrayPluck([fs, "b", 0], arr);

expect(a.toJSON()).toEqual({
type: "array-pluck",
op_stack: [
ArrayPluck.Operation.future("attr", "FutureStringId"),
ArrayPluck.Operation.key("attr", "b"),
ArrayPluck.Operation.key("item", 0),
],
target_future_id: "FutureArrayId",
});
});

test(".referencedFutures", () => {
const arr = new TestFutureArray(
new Trace([], staticNode([{ a: { b: [1] } }])), "FutureArrayId"
);
const fs = new FutureString(new Trace([], staticNode("a")), "FutureStringId");

const f = new ArrayPluck([fs, "b", 0], arr);
expect(f.referencedFutures()).toEqual([arr, fs]);
});
});

describe("FutureString", () => {
test(".concat (static)", () => {
const s = FutureString.concat("a");
@@ -262,5 +319,29 @@ describe("Future", () => {
// @ts-expect-error (protected access)
expect(a2.directive).toEqual(new ArrayConcat([a1, "b", ["c"]]));
});

test(".pluck (static)", () => {
const arr = FutureArray.concat({ a: 1 } as any);
const p = FutureArray.pluck(["a"], arr);
expect(p).toBeInstanceOf(FutureArray);
// @ts-expect-error (protected access)
expect(p.directive).toEqual(new ArrayPluck(["a"], arr));
});

test(".pluck (instance)", () => {
const arr = FutureArray.concat({ a: 1 } as any);
const p = arr.pluck("a");
expect(p).toBeInstanceOf(FutureArray);
// @ts-expect-error (protected access)
expect(p.directive).toEqual(new ArrayPluck(["a"], arr));

// when using "json path" synxtax
const arr2 = FutureArray.concat({ a: { b: [1] } } as any);
const p2 = arr2.pluck("a.b[0]");
expect(p2).toBeInstanceOf(FutureArray);
// @ts-expect-error (protected access)
expect(p2.directive).toEqual(new ArrayPluck(["a", "b", 0], arr2));
expect(p2.result()).resolves.toEqual([1]);
});
});
});
Loading