Skip to content

Commit

Permalink
Added the Array Length node. (#521)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexBxl authored Nov 14, 2024
1 parent ace498f commit c4edd77
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/quick-buckets-double.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tokens-studio/graph-engine": minor
---

An Array Length node was added to get the length of an array.
2 changes: 2 additions & 0 deletions packages/graph-engine/src/nodes/array/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import find from './find.js';
import flatten from './flatten.js';
import indexArray from './indexArray.js';
import inject from './inject.js';
import length from './length.js';
import push from './push.js';
import replace from './replace.js';
import reverse from './reverse.js';
Expand All @@ -21,6 +22,7 @@ export const nodes = [
flatten,
indexArray,
inject,
length,
push,
replace,
reverse,
Expand Down
33 changes: 33 additions & 0 deletions packages/graph-engine/src/nodes/array/length.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { AnyArraySchema, NumberSchema } from '../../schemas/index.js';
import { INodeDefinition, ToInput, ToOutput } from '../../index.js';
import { Node } from '../../programmatic/node.js';

export default class NodeDefinition<T> extends Node {
static title = 'Array Length';
static type = 'studio.tokens.array.length';
static description = 'Determines the length of an array.';

declare inputs: ToInput<{
array: T[];
}>;

declare outputs: ToOutput<{
length: number;
}>;

constructor(props: INodeDefinition) {
super(props);
this.addInput('array', {
type: AnyArraySchema
});
this.addOutput('length', {
type: NumberSchema
});
}

execute(): void | Promise<void> {
const { array } = this.getAllInputs();

this.outputs.length.set(array.length);
}
}
16 changes: 16 additions & 0 deletions packages/graph-engine/tests/suites/nodes/array/length.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Graph } from '../../../../src/graph/graph.js';
import { describe, expect, test } from 'vitest';
import Node from '../../../../src/nodes/array/length.js';

describe('array/length', () => {
test('return length of array', async () => {
const graph = new Graph();
const node = new Node({ graph });

node.inputs.array.setValue([4, 5, 6]);

await node.execute();

expect(node.outputs.length.value).to.equal(3);
});
});

0 comments on commit c4edd77

Please sign in to comment.