Skip to content

Commit

Permalink
Add Spacing to stringify output. (#3202)
Browse files Browse the repository at this point in the history
* add spacing to stringify output.

* fix test in combo.js by adding replacer to stringify.
  • Loading branch information
Amr Elghobary committed Oct 4, 2021
1 parent 29b4c69 commit 00a2f59
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions packages/sourcecred/src/util/combo.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Simple parser combinator library for structured types rather than
// bytestring parsing.

import stringify from "json-stable-stringify";

export type JsonObject =
| string
| number
Expand All @@ -25,9 +27,11 @@ export class Parser<+T> {
constructor(f: (JsonObject) => ParseResult<T>) {
this._f = f;
}

parse(raw: JsonObject): ParseResult<T> {
return this._f(raw);
}

parseOrThrow(raw: JsonObject): T {
const result = this.parse(raw);
if (result.ok) {
Expand Down Expand Up @@ -201,10 +205,23 @@ export function fmap<T, U>(p: Parser<T>, f: (T) => U): Parser<U> {
});
}

// replacer for stringify.JSON, in order to replace empty array with just `[]`.
//
// this replacer function can be extended and universally be used with other
// aspect like empty objects.
function emptyArrayReplacer(key: string, value: any) {
// check if the array is empty.
if (Array.isArray(value) && value.length === 0) {
return [];
}

return value;
}

// Create a parser that tries each of the given parsers on the same
// input, taking the first successful parse or failing if all parsers
// fail. In the failure case, the provided `errorFn` will be called with
// the error messages from all the subparsers to form the resulting
// the error messages from all the sub-parsers to form the resulting
// error; the default error function includes the full text of all the
// error messages, but a user-supplied error function may act with
// domain-specific precision.
Expand All @@ -231,7 +248,10 @@ export function fmap<T, U>(p: Parser<T>, f: (T) => U): Parser<U> {
export function orElse<T: $ReadOnlyArray<Parser<mixed>>>(
parsers: T,
errorFn?: (string[]) => string = (errors) =>
`no parse matched: ${JSON.stringify(errors)}`
`no parse matched: ${stringify(errors, {
replacer: emptyArrayReplacer,
spacer: 4,
})}`
): Parser<$ElementType<$TupleMap<T, ExtractParserOutput>, number>> {
return new Parser((x) => {
const errors = [];
Expand Down Expand Up @@ -284,6 +304,7 @@ export function rename<T>(oldKey: string, parser: Parser<T>): RenameField<T> {

class RenameFieldImpl<+T> extends Parser<T> {
+oldKey: string;

constructor(oldKey: string, parser: Parser<T>) {
super(parser._f);
this.oldKey = oldKey;
Expand Down

0 comments on commit 00a2f59

Please sign in to comment.