Skip to content

Commit

Permalink
todo
Browse files Browse the repository at this point in the history
  • Loading branch information
janmazak committed Dec 18, 2023
1 parent e61e50a commit b172ab5
Show file tree
Hide file tree
Showing 3 changed files with 360 additions and 270 deletions.
25 changes: 23 additions & 2 deletions src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,8 @@ export const parseArray = <T>(
}

const areUnique = <T>(items: T[], serialize: Serializer<T>): boolean => {
const s = new Set<Buffer>(items.map(serialize).map(encodeToCbor))
const encoded: Buffer[] = items.map(serialize).map(encodeToCbor)
const s = new Set<string>(encoded.map((buffer) => buffer.toString('hex')))
return s.size === items.length
}

Expand Down Expand Up @@ -274,7 +275,7 @@ export const parseCddlNonEmptyOrderedSet = <T>(
* // returns [123N, -1N]
* parseTuple([123, -1], InvalidDataReason.INVALID, parseUint64, parseInt64)
*/
export const parseTuple = <T extends unknown[]>(
export const parseTupleWithUndefined = <T extends unknown[]>(
data: unknown,
errMsg: ParseErrorReason,
...parsers: {[K in keyof T]: Parser<T[K]>}
Expand All @@ -285,6 +286,26 @@ export const parseTuple = <T extends unknown[]>(
return parsers.map((parser, index) => parser(data[index])) as T
}

/**
* Parses the data as an array of length of the provided parsers.
* If the number of provided parsers exceeds the length of parsed array,
* an error is thrown.
*
* @example
* // returns [123N, -1N]
* parseTuple([123, -1], InvalidDataReason.INVALID, parseUint64, parseInt64)
*/
export const parseTuple = <T extends unknown[]>(
data: unknown,
errMsg: ParseErrorReason,
...parsers: {[K in keyof T]: Parser<T[K]>}
): T => {
validate(isArray(data), errMsg)
validate(data.length === parsers.length, errMsg)

return parsers.map((parser, index) => parser(data[index])) as T
}

export const parseOptional = <T>(
data: unknown,
parser: Parser<T>,
Expand Down
Loading

0 comments on commit b172ab5

Please sign in to comment.