Skip to content

Commit

Permalink
Added a 'concat' operator.
Browse files Browse the repository at this point in the history
  • Loading branch information
iwoplaza committed Dec 25, 2023
1 parent b713a60 commit 6bd5140
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/describe/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,13 @@ export const keyed = <K extends string, P extends ISchema<unknown>>(
key: K,
inner: (ref: IUnstableSchema<Ref<K>>) => P,
) => new KeyedSchema(key, inner);

export const concat = <Objs extends ObjectSchema<{ [key: string]: unknown }>[]>(
objs: Objs,
) => {
return new ObjectSchema(
Object.fromEntries(
objs.map(({ properties }) => Object.entries(properties)).flat(),
) as unknown as SchemaMap<Objs[number]['_infered']>,
);
};
62 changes: 61 additions & 1 deletion src/test/object.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as chai from 'chai';
import { encodeAndDecode, makeIO } from './helpers/mock';
import { generic, genericEnum, object, optional } from '../describe';
import { concat, generic, genericEnum, object, optional } from '../describe';
import { byte, i32, string, MaxValue } from '../structure';
import { Parsed } from '../utilityTypes';

Expand Down Expand Up @@ -128,4 +128,64 @@ describe('ObjectSchema', () => {
expect(input.readInt32()).to.equal(3); // c
expect(input.readInt32()).to.equal(2); // b
});

it('allows to extend it with more properties', () => {
const schema = object({
a: i32,
b: i32,
});

const extended = concat([
schema,
object({
c: i32,
d: i32,
}),
]);

const value: Parsed<typeof extended> = {
a: 1,
b: 2,
c: 3,
d: 4,
};

const { output, input } = makeIO(extended.measure(value).size);
extended.write(output, value);

expect(input.readInt32()).to.equal(1); // a
expect(input.readInt32()).to.equal(2); // b
expect(input.readInt32()).to.equal(3); // c
expect(input.readInt32()).to.equal(4); // d
});

it('allows to prepend it with more properties', () => {
const schema = object({
a: i32,
b: i32,
});

const prepended = concat([
object({
c: i32,
d: i32,
}),
schema,
]);

const value: Parsed<typeof prepended> = {
a: 1,
b: 2,
c: 3,
d: 4,
};

const { output, input } = makeIO(prepended.measure(value).size);
prepended.write(output, value);

expect(input.readInt32()).to.equal(3); // c
expect(input.readInt32()).to.equal(4); // d
expect(input.readInt32()).to.equal(1); // a
expect(input.readInt32()).to.equal(2); // b
});
});

0 comments on commit 6bd5140

Please sign in to comment.