ts-std-lib
Version:
A standard library for typescript
26 lines (19 loc) • 679 B
text/typescript
import { IJsonSerializer, jsonSerializer } from './IJsonSerializer';
import { Json, JsonArray } from './Json';
import { Type } from '../../Type';
import { UnexpectedJsonError } from './UnexpectedJsonError';
/**
* Json serializer for the native Set class
*/
export class SetJsonSerializer<T extends Json> implements IJsonSerializer<ReadonlySet<T>> {
public readonly [jsonSerializer] = true;
public serialize(object: ReadonlySet<T>): Json {
return [...object] as JsonArray;
}
public deserialize(json: Json): ReadonlySet<T> {
if (!Type.isArray(json)) {
throw new UnexpectedJsonError(json);
}
return new Set(json as Iterable<T>);
}
}