Skip to content

Commit

Permalink
Option to limit amount of unrolled elements
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeche committed Aug 21, 2019
1 parent f46ccab commit b43998f
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/abbreviation/src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default function convert(abbr: TokenGroup, options: ParserOptions = {}):
inserted: false,
repeaters: [],
text: options.text,
repeatGuard: options.maxRepeat || Number.POSITIVE_INFINITY,
getText(pos) {
const value = Array.isArray(options.text)
? (pos != null ? options.text[pos] : options.text.join('\n'))
Expand Down Expand Up @@ -65,6 +66,12 @@ function convertStatement(node: TokenStatement, state: ConvertState): Abbreviati
}

result = result.concat(items);

// We should output at least one repeated item even if it’s reached
// repeat limit
if (--state.repeatGuard <= 0) {
break;
}
}

state.repeaters.pop();
Expand Down
2 changes: 2 additions & 0 deletions packages/abbreviation/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import { Field, Repeater } from './tokenizer';
export interface ParserOptions {
text?: string | string[];
variables?: { [name: string]: string };
maxRepeat?: number;
}

export interface ConvertState {
inserted: boolean;
text?: string | string[];
repeatGuard: number;

/** Context repeaters, e.g. all actual repeaters from parent */
repeaters: Repeater[];
Expand Down
7 changes: 7 additions & 0 deletions packages/abbreviation/test/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,11 @@ describe('Convert token abbreviations', () => {
equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>');
equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>');
});

it('limit unroll', () => {
// Limit amount of repeated elements
equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>');
equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>');
equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>');
});
});
3 changes: 3 additions & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ interface ResolvedConfig extends BaseConfig {

/** Text to wrap with abbreviation */
text?: string | string[];

/** Max amount of repeated elements (fool proof) */
maxRepeat?: number;
}

export type Config = ResolvedConfig & { options: Options };
Expand Down

0 comments on commit b43998f

Please sign in to comment.