Refactor to improve iterations
- Use function abstractions (such as map, reduce, filter etc.) over for-of loops to gain benefits of having less side effects and easier readability. - Enable `downLevelIterations` for writing modern code with lazy evaluation. - Refactor for of loops to named abstractions to clearly express their intentions without needing to analyse the loop itself. - Add missing cases for changes that had no tests.
This commit is contained in:
@@ -42,15 +42,14 @@ export class CodeChangedEvent implements ICodeChangedEvent {
|
||||
|
||||
function ensureAllPositionsExist(script: string, positions: ReadonlyArray<ICodePosition>) {
|
||||
const totalLines = script.split(/\r\n|\r|\n/).length;
|
||||
for (const position of positions) {
|
||||
if (position.endLine > totalLines) {
|
||||
const missingPositions = positions.filter((position) => position.endLine > totalLines);
|
||||
if (missingPositions.length > 0) {
|
||||
throw new Error(
|
||||
`script end line (${position.endLine}) is out of range.`
|
||||
+ `(total code lines: ${totalLines}`,
|
||||
`Out of range script end line: "${missingPositions.map((pos) => pos.endLine).join('", "')}"`
|
||||
+ `(total code lines: ${totalLines}).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getChangedScripts(
|
||||
oldScripts: ReadonlyArray<SelectedScript>,
|
||||
|
||||
@@ -17,9 +17,7 @@ export abstract class CodeBuilder implements ICodeBuilder {
|
||||
return this;
|
||||
}
|
||||
const lines = code.match(/[^\r\n]+/g);
|
||||
for (const line of lines) {
|
||||
this.lines.push(line);
|
||||
}
|
||||
this.lines.push(...lines);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -19,15 +19,14 @@ export class UserScriptGenerator implements IUserScriptGenerator {
|
||||
): IUserScript {
|
||||
if (!selectedScripts) { throw new Error('undefined scripts'); }
|
||||
if (!scriptingDefinition) { throw new Error('undefined definition'); }
|
||||
let scriptPositions = new Map<SelectedScript, ICodePosition>();
|
||||
if (!selectedScripts.length) {
|
||||
return { code: '', scriptPositions };
|
||||
return { code: '', scriptPositions: new Map<SelectedScript, ICodePosition>() };
|
||||
}
|
||||
let builder = this.codeBuilderFactory.create(scriptingDefinition.language);
|
||||
builder = initializeCode(scriptingDefinition.startCode, builder);
|
||||
for (const selection of selectedScripts) {
|
||||
scriptPositions = appendSelection(selection, scriptPositions, builder);
|
||||
}
|
||||
const scriptPositions = selectedScripts.reduce((result, selection) => {
|
||||
return appendSelection(selection, result, builder);
|
||||
}, new Map<SelectedScript, ICodePosition>());
|
||||
const code = finalizeCode(builder, scriptingDefinition.endCode);
|
||||
return { code, scriptPositions };
|
||||
}
|
||||
|
||||
@@ -17,12 +17,10 @@ export class UserSelection implements IUserSelection {
|
||||
selectedScripts: ReadonlyArray<SelectedScript>,
|
||||
) {
|
||||
this.scripts = new InMemoryRepository<string, SelectedScript>();
|
||||
if (selectedScripts && selectedScripts.length > 0) {
|
||||
for (const script of selectedScripts) {
|
||||
this.scripts.addItem(script);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public areAllSelected(category: ICategory): boolean {
|
||||
if (this.selectedScripts.length === 0) {
|
||||
@@ -58,18 +56,19 @@ export class UserSelection implements IUserSelection {
|
||||
}
|
||||
|
||||
public addOrUpdateAllInCategory(categoryId: number, revert = false): void {
|
||||
const category = this.collection.findCategory(categoryId);
|
||||
const scriptsToAddOrUpdate = category.getAllScriptsRecursively()
|
||||
const scriptsToAddOrUpdate = this.collection
|
||||
.findCategory(categoryId)
|
||||
.getAllScriptsRecursively()
|
||||
.filter(
|
||||
(script) => !this.scripts.exists(script.id)
|
||||
|| this.scripts.getById(script.id).revert !== revert,
|
||||
);
|
||||
)
|
||||
.map((script) => new SelectedScript(script, revert));
|
||||
if (!scriptsToAddOrUpdate.length) {
|
||||
return;
|
||||
}
|
||||
for (const script of scriptsToAddOrUpdate) {
|
||||
const selectedScript = new SelectedScript(script, revert);
|
||||
this.scripts.addOrUpdateItem(selectedScript);
|
||||
this.scripts.addOrUpdateItem(script);
|
||||
}
|
||||
this.changed.notify(this.scripts.getItems());
|
||||
}
|
||||
@@ -106,11 +105,12 @@ export class UserSelection implements IUserSelection {
|
||||
}
|
||||
|
||||
public selectAll(): void {
|
||||
for (const script of this.collection.getAllScripts()) {
|
||||
if (!this.scripts.exists(script.id)) {
|
||||
const selection = new SelectedScript(script, false);
|
||||
this.scripts.addItem(selection);
|
||||
}
|
||||
const scriptsToSelect = this.collection
|
||||
.getAllScripts()
|
||||
.filter((script) => !this.scripts.exists(script.id))
|
||||
.map((script) => new SelectedScript(script, false));
|
||||
for (const script of scriptsToSelect) {
|
||||
this.scripts.addItem(script);
|
||||
}
|
||||
this.changed.notify(this.scripts.getItems());
|
||||
}
|
||||
@@ -135,10 +135,11 @@ export class UserSelection implements IUserSelection {
|
||||
.forEach((scriptId) => this.scripts.removeItem(scriptId));
|
||||
}
|
||||
// Select from unselected scripts
|
||||
const unselectedScripts = scripts.filter((script) => !this.scripts.exists(script.id));
|
||||
const unselectedScripts = scripts
|
||||
.filter((script) => !this.scripts.exists(script.id))
|
||||
.map((script) => new SelectedScript(script, false));
|
||||
for (const toSelect of unselectedScripts) {
|
||||
const selection = new SelectedScript(toSelect, false);
|
||||
this.scripts.addItem(selection);
|
||||
this.scripts.addItem(toSelect);
|
||||
}
|
||||
this.changed.notify(this.scripts.getItems());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { CollectionData } from 'js-yaml-loader!@/*';
|
||||
import { Category } from '@/domain/Category';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { ICategoryCollection } from '@/domain/ICategoryCollection';
|
||||
import { CategoryCollection } from '@/domain/CategoryCollection';
|
||||
@@ -18,11 +17,7 @@ export function parseCategoryCollection(
|
||||
const scripting = new ScriptingDefinitionParser()
|
||||
.parse(content.scripting, info);
|
||||
const context = new CategoryCollectionParseContext(content.functions, scripting);
|
||||
const categories = new Array<Category>();
|
||||
for (const action of content.actions) {
|
||||
const category = parseCategory(action, context);
|
||||
categories.push(category);
|
||||
}
|
||||
const categories = content.actions.map((action) => parseCategory(action, context));
|
||||
const os = osParser.parseEnum(content.os, 'os');
|
||||
const collection = new CategoryCollection(
|
||||
os,
|
||||
|
||||
@@ -9,11 +9,6 @@ import { parseScript } from './Script/ScriptParser';
|
||||
|
||||
let categoryIdCounter = 0;
|
||||
|
||||
interface ICategoryChildren {
|
||||
subCategories: Category[];
|
||||
subScripts: Script[];
|
||||
}
|
||||
|
||||
export function parseCategory(
|
||||
category: CategoryData,
|
||||
context: ICategoryCollectionParseContext,
|
||||
@@ -48,6 +43,11 @@ function ensureValid(category: CategoryData) {
|
||||
}
|
||||
}
|
||||
|
||||
interface ICategoryChildren {
|
||||
subCategories: Category[];
|
||||
subScripts: Script[];
|
||||
}
|
||||
|
||||
function parseCategoryChild(
|
||||
data: CategoryOrScriptData,
|
||||
children: ICategoryChildren,
|
||||
|
||||
@@ -56,14 +56,13 @@ function compileExpressions(
|
||||
function extractRequiredParameterNames(
|
||||
expressions: readonly IExpression[],
|
||||
): string[] {
|
||||
const usedParameterNames = expressions
|
||||
return expressions
|
||||
.map((e) => e.parameters.all
|
||||
.filter((p) => !p.isOptional)
|
||||
.map((p) => p.name))
|
||||
.filter((p) => p)
|
||||
.flat();
|
||||
const uniqueParameterNames = Array.from(new Set(usedParameterNames));
|
||||
return uniqueParameterNames;
|
||||
.filter(Boolean) // Remove empty or undefined
|
||||
.flat()
|
||||
.filter((name, index, array) => array.indexOf(name) === index); // Remove duplicates
|
||||
}
|
||||
|
||||
function ensureParamsUsedInCodeHasArgsProvided(
|
||||
|
||||
@@ -16,13 +16,8 @@ export class CompositeExpressionParser implements IExpressionParser {
|
||||
}
|
||||
|
||||
public findExpressions(code: string): IExpression[] {
|
||||
const expressions = new Array<IExpression>();
|
||||
for (const parser of this.leafs) {
|
||||
const newExpressions = parser.findExpressions(code);
|
||||
if (newExpressions && newExpressions.length) {
|
||||
expressions.push(...newExpressions);
|
||||
}
|
||||
}
|
||||
return expressions;
|
||||
return this.leafs.flatMap(
|
||||
(parser) => parser.findExpressions(code) || [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,35 +18,42 @@ export abstract class RegexParser implements IExpressionParser {
|
||||
if (!code) {
|
||||
throw new Error('undefined code');
|
||||
}
|
||||
const matches = Array.from(code.matchAll(this.regex));
|
||||
const matches = code.matchAll(this.regex);
|
||||
for (const match of matches) {
|
||||
const startPos = match.index;
|
||||
const endPos = startPos + match[0].length;
|
||||
let position: ExpressionPosition;
|
||||
try {
|
||||
position = new ExpressionPosition(startPos, endPos);
|
||||
} catch (error) {
|
||||
throw new Error(`[${this.constructor.name}] invalid script position: ${error.message}\nRegex ${this.regex}\nCode: ${code}`);
|
||||
}
|
||||
const primitiveExpression = this.buildExpression(match);
|
||||
const parameters = getParameters(primitiveExpression);
|
||||
const position = this.doOrRethrow(() => createPosition(match), 'invalid script position', code);
|
||||
const parameters = createParameters(primitiveExpression);
|
||||
const expression = new Expression(position, primitiveExpression.evaluator, parameters);
|
||||
yield expression;
|
||||
}
|
||||
}
|
||||
|
||||
private doOrRethrow<T>(action: () => T, errorText: string, code: string): T {
|
||||
try {
|
||||
return action();
|
||||
} catch (error) {
|
||||
throw new Error(`[${this.constructor.name}] ${errorText}: ${error.message}\nRegex: ${this.regex}\nCode: ${code}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createPosition(match: RegExpMatchArray): ExpressionPosition {
|
||||
const startPos = match.index;
|
||||
const endPos = startPos + match[0].length;
|
||||
return new ExpressionPosition(startPos, endPos);
|
||||
}
|
||||
|
||||
function createParameters(
|
||||
expression: IPrimitiveExpression,
|
||||
): FunctionParameterCollection {
|
||||
return (expression.parameters || [])
|
||||
.reduce((parameters, parameter) => {
|
||||
parameters.addParameter(parameter);
|
||||
return parameters;
|
||||
}, new FunctionParameterCollection());
|
||||
}
|
||||
|
||||
export interface IPrimitiveExpression {
|
||||
evaluator: ExpressionEvaluator;
|
||||
parameters?: readonly IFunctionParameter[];
|
||||
}
|
||||
|
||||
function getParameters(
|
||||
expression: IPrimitiveExpression,
|
||||
): FunctionParameterCollection {
|
||||
const parameters = new FunctionParameterCollection();
|
||||
for (const parameter of expression.parameters || []) {
|
||||
parameters.addParameter(parameter);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
@@ -8,11 +8,9 @@ export class PipelineCompiler implements IPipelineCompiler {
|
||||
ensureValidArguments(value, pipeline);
|
||||
const pipeNames = extractPipeNames(pipeline);
|
||||
const pipes = pipeNames.map((pipeName) => this.factory.get(pipeName));
|
||||
let valueInCompilation = value;
|
||||
for (const pipe of pipes) {
|
||||
valueInCompilation = pipe.apply(valueInCompilation);
|
||||
}
|
||||
return valueInCompilation;
|
||||
return pipes.reduce((previousValue, pipe) => {
|
||||
return pipe.apply(previousValue);
|
||||
}, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,11 +47,8 @@ interface ICompiledFunctionCall {
|
||||
}
|
||||
|
||||
function compileCallSequence(context: ICompilationContext): ICompiledFunctionCall {
|
||||
const compiledFunctions = new Array<ICompiledFunctionCall>();
|
||||
for (const call of context.callSequence) {
|
||||
const compiledCode = compileSingleCall(call, context);
|
||||
compiledFunctions.push(...compiledCode);
|
||||
}
|
||||
const compiledFunctions = context.callSequence
|
||||
.flatMap((call) => compileSingleCall(call, context));
|
||||
return {
|
||||
code: merge(compiledFunctions.map((f) => f.code)),
|
||||
revertCode: merge(compiledFunctions.map((f) => f.revertCode)),
|
||||
@@ -94,14 +91,17 @@ function compileArgs(
|
||||
args: IReadOnlyFunctionCallArgumentCollection,
|
||||
compiler: IExpressionsCompiler,
|
||||
): IReadOnlyFunctionCallArgumentCollection {
|
||||
const compiledArgs = new FunctionCallArgumentCollection();
|
||||
for (const parameterName of argsToCompile.getAllParameterNames()) {
|
||||
return argsToCompile
|
||||
.getAllParameterNames()
|
||||
.map((parameterName) => {
|
||||
const { argumentValue } = argsToCompile.getArgument(parameterName);
|
||||
const compiledValue = compiler.compileExpressions(argumentValue, args);
|
||||
const newArgument = new FunctionCallArgument(parameterName, compiledValue);
|
||||
compiledArgs.addArgument(newArgument);
|
||||
}
|
||||
return new FunctionCallArgument(parameterName, compiledValue);
|
||||
})
|
||||
.reduce((compiledArgs, arg) => {
|
||||
compiledArgs.addArgument(arg);
|
||||
return compiledArgs;
|
||||
}, new FunctionCallArgumentCollection());
|
||||
}
|
||||
|
||||
function merge(codeParts: readonly string[]): string {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FunctionCallData, FunctionCallsData } from 'js-yaml-loader!@/*';
|
||||
import { FunctionCallData, FunctionCallsData, FunctionCallParametersData } from 'js-yaml-loader!@/*';
|
||||
import { IFunctionCall } from './IFunctionCall';
|
||||
import { FunctionCallArgumentCollection } from './Argument/FunctionCallArgumentCollection';
|
||||
import { FunctionCallArgument } from './Argument/FunctionCallArgument';
|
||||
@@ -26,10 +26,17 @@ function parseFunctionCall(call: FunctionCallData): IFunctionCall {
|
||||
if (!call) {
|
||||
throw new Error('undefined function call');
|
||||
}
|
||||
const args = new FunctionCallArgumentCollection();
|
||||
for (const parameterName of Object.keys(call.parameters || {})) {
|
||||
const arg = new FunctionCallArgument(parameterName, call.parameters[parameterName]);
|
||||
const callArgs = parseArgs(call.parameters);
|
||||
return new FunctionCall(call.function, callArgs);
|
||||
}
|
||||
|
||||
function parseArgs(
|
||||
parameters: FunctionCallParametersData,
|
||||
): FunctionCallArgumentCollection {
|
||||
return Object.keys(parameters || {})
|
||||
.map((parameterName) => new FunctionCallArgument(parameterName, parameters[parameterName]))
|
||||
.reduce((args, arg) => {
|
||||
args.addArgument(arg);
|
||||
}
|
||||
return new FunctionCall(call.function, args);
|
||||
return args;
|
||||
}, new FunctionCallArgumentCollection());
|
||||
}
|
||||
|
||||
@@ -20,11 +20,12 @@ export class SharedFunctionsParser implements ISharedFunctionsParser {
|
||||
return collection;
|
||||
}
|
||||
ensureValidFunctions(functions);
|
||||
for (const func of functions) {
|
||||
const sharedFunction = parseFunction(func);
|
||||
collection.addFunction(sharedFunction);
|
||||
}
|
||||
return collection;
|
||||
return functions
|
||||
.map((func) => parseFunction(func))
|
||||
.reduce((acc, func) => {
|
||||
acc.addFunction(func);
|
||||
return acc;
|
||||
}, collection);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,20 +41,21 @@ function parseFunction(data: FunctionData): ISharedFunction {
|
||||
}
|
||||
|
||||
function parseParameters(data: FunctionData): IReadOnlyFunctionParameterCollection {
|
||||
const parameters = new FunctionParameterCollection();
|
||||
if (!data.parameters) {
|
||||
return parameters;
|
||||
}
|
||||
for (const parameterData of data.parameters) {
|
||||
const isOptional = parameterData.optional || false;
|
||||
return (data.parameters || [])
|
||||
.map((parameter) => {
|
||||
try {
|
||||
const parameter = new FunctionParameter(parameterData.name, isOptional);
|
||||
parameters.addParameter(parameter);
|
||||
return new FunctionParameter(
|
||||
parameter.name,
|
||||
parameter.optional || false,
|
||||
);
|
||||
} catch (err) {
|
||||
throw new Error(`"${data.name}": ${err.message}`);
|
||||
}
|
||||
}
|
||||
})
|
||||
.reduce((parameters, parameter) => {
|
||||
parameters.addParameter(parameter);
|
||||
return parameters;
|
||||
}, new FunctionParameterCollection());
|
||||
}
|
||||
|
||||
function hasCode(data: FunctionData): boolean {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getEnumNames, getEnumValues, assertInRange } from '@/application/Common/Enum';
|
||||
import { getEnumValues, assertInRange } from '@/application/Common/Enum';
|
||||
import { IEntity } from '../infrastructure/Entity/IEntity';
|
||||
import { ICategory } from './ICategory';
|
||||
import { IScript } from './IScript';
|
||||
@@ -57,16 +57,12 @@ export class CategoryCollection implements ICategoryCollection {
|
||||
}
|
||||
|
||||
function ensureNoDuplicates<TKey>(entities: ReadonlyArray<IEntity<TKey>>) {
|
||||
const totalOccurrencesById = new Map<TKey, number>();
|
||||
for (const entity of entities) {
|
||||
totalOccurrencesById.set(entity.id, (totalOccurrencesById.get(entity.id) || 0) + 1);
|
||||
}
|
||||
const duplicatedIds = new Array<TKey>();
|
||||
totalOccurrencesById.forEach((index, id) => {
|
||||
if (index > 1) {
|
||||
duplicatedIds.push(id);
|
||||
}
|
||||
});
|
||||
const isUniqueInArray = (id: TKey, index: number, array: readonly TKey[]) => array
|
||||
.findIndex((otherId) => otherId === id) !== index;
|
||||
const duplicatedIds = entities
|
||||
.map((entity) => entity.id)
|
||||
.filter((id, index, array) => !isUniqueInArray(id, index, array))
|
||||
.filter(isUniqueInArray);
|
||||
if (duplicatedIds.length > 0) {
|
||||
const duplicatedIdsText = duplicatedIds.map((id) => `"${id}"`).join(',');
|
||||
throw new Error(
|
||||
@@ -96,48 +92,37 @@ function ensureValidScripts(allScripts: readonly IScript[]) {
|
||||
if (!allScripts || allScripts.length === 0) {
|
||||
throw new Error('must consist of at least one script');
|
||||
}
|
||||
for (const level of getEnumValues(RecommendationLevel)) {
|
||||
if (allScripts.every((script) => script.level !== level)) {
|
||||
throw new Error(`none of the scripts are recommended as ${RecommendationLevel[level]}`);
|
||||
}
|
||||
const missingRecommendationLevels = getEnumValues(RecommendationLevel)
|
||||
.filter((level) => allScripts.every((script) => script.level !== level));
|
||||
if (missingRecommendationLevels.length > 0) {
|
||||
throw new Error('none of the scripts are recommended as'
|
||||
+ ` "${missingRecommendationLevels.map((level) => RecommendationLevel[level]).join(', "')}".`);
|
||||
}
|
||||
}
|
||||
|
||||
function flattenApplication(categories: ReadonlyArray<ICategory>): [ICategory[], IScript[]] {
|
||||
const allCategories = new Array<ICategory>();
|
||||
const allScripts = new Array<IScript>();
|
||||
flattenCategories(categories, allCategories, allScripts);
|
||||
return [
|
||||
allCategories,
|
||||
allScripts,
|
||||
];
|
||||
}
|
||||
|
||||
function flattenCategories(
|
||||
function flattenApplication(
|
||||
categories: ReadonlyArray<ICategory>,
|
||||
allCategories: ICategory[],
|
||||
allScripts: IScript[],
|
||||
): IQueryableCollection {
|
||||
if (!categories || categories.length === 0) {
|
||||
return;
|
||||
}
|
||||
for (const category of categories) {
|
||||
allCategories.push(category);
|
||||
flattenScripts(category.scripts, allScripts);
|
||||
flattenCategories(category.subCategories, allCategories, allScripts);
|
||||
}
|
||||
}
|
||||
|
||||
function flattenScripts(
|
||||
scripts: ReadonlyArray<IScript>,
|
||||
allScripts: IScript[],
|
||||
): IScript[] {
|
||||
if (!scripts) {
|
||||
return;
|
||||
}
|
||||
for (const script of scripts) {
|
||||
allScripts.push(script);
|
||||
}
|
||||
): [ICategory[], IScript[]] {
|
||||
const [subCategories, subScripts] = (categories || [])
|
||||
// Parse children
|
||||
.map((category) => flattenApplication(category.subCategories))
|
||||
// Flatten results
|
||||
.reduce(([previousCategories, previousScripts], [currentCategories, currentScripts]) => {
|
||||
return [
|
||||
[...previousCategories, ...currentCategories],
|
||||
[...previousScripts, ...currentScripts],
|
||||
];
|
||||
}, [new Array<ICategory>(), new Array<IScript>()]);
|
||||
return [
|
||||
[
|
||||
...(categories || []),
|
||||
...subCategories,
|
||||
],
|
||||
[
|
||||
...(categories || []).flatMap((category) => category.scripts || []),
|
||||
...subScripts,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
function makeQueryable(
|
||||
@@ -154,13 +139,15 @@ function makeQueryable(
|
||||
function groupByLevel(
|
||||
allScripts: readonly IScript[],
|
||||
): Map<RecommendationLevel, readonly IScript[]> {
|
||||
const map = new Map<RecommendationLevel, readonly IScript[]>();
|
||||
for (const levelName of getEnumNames(RecommendationLevel)) {
|
||||
const level = RecommendationLevel[levelName];
|
||||
const scripts = allScripts.filter(
|
||||
return getEnumValues(RecommendationLevel)
|
||||
.map((level) => ({
|
||||
level,
|
||||
scripts: allScripts.filter(
|
||||
(script) => script.level !== undefined && script.level <= level,
|
||||
);
|
||||
map.set(level, scripts);
|
||||
}
|
||||
),
|
||||
}))
|
||||
.reduce((map, group) => {
|
||||
map.set(group.level, group.scripts);
|
||||
return map;
|
||||
}, new Map<RecommendationLevel, readonly IScript[]>());
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ export class EventSource<T> implements IEventSource<T> {
|
||||
}
|
||||
|
||||
public notify(data: T) {
|
||||
for (const handler of Array.from(this.handlers.values())) {
|
||||
for (const handler of this.handlers.values()) {
|
||||
handler(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ export class SelectionTypeHandler {
|
||||
}
|
||||
|
||||
public getCurrentSelectionType(): SelectionType {
|
||||
for (const [type, selector] of Array.from(selectors.entries())) {
|
||||
for (const [type, selector] of selectors.entries()) {
|
||||
if (selector.isSelected(this.state)) {
|
||||
return type;
|
||||
}
|
||||
|
||||
@@ -3,12 +3,7 @@ import { ICategoryCollection } from '@/domain/ICategoryCollection';
|
||||
import { INode, NodeType } from './SelectableTree/Node/INode';
|
||||
|
||||
export function parseAllCategories(collection: ICategoryCollection): INode[] | undefined {
|
||||
const nodes = new Array<INode>();
|
||||
for (const category of collection.actions) {
|
||||
const children = parseCategoryRecursively(category);
|
||||
nodes.push(convertCategoryToNode(category, children));
|
||||
}
|
||||
return nodes;
|
||||
return createCategoryNodes(collection.actions);
|
||||
}
|
||||
|
||||
export function parseSingleCategory(
|
||||
@@ -43,31 +38,21 @@ function parseCategoryRecursively(
|
||||
if (!parentCategory) {
|
||||
throw new Error('parentCategory is undefined');
|
||||
}
|
||||
let nodes = new Array<INode>();
|
||||
nodes = addCategories(parentCategory.subCategories, nodes);
|
||||
nodes = addScripts(parentCategory.scripts, nodes);
|
||||
return nodes;
|
||||
return [
|
||||
...createCategoryNodes(parentCategory.subCategories),
|
||||
...createScriptNodes(parentCategory.scripts),
|
||||
];
|
||||
}
|
||||
|
||||
function addScripts(scripts: ReadonlyArray<IScript>, nodes: INode[]): INode[] {
|
||||
if (!scripts || scripts.length === 0) {
|
||||
return nodes;
|
||||
}
|
||||
for (const script of scripts) {
|
||||
nodes.push(convertScriptToNode(script));
|
||||
}
|
||||
return nodes;
|
||||
function createScriptNodes(scripts: ReadonlyArray<IScript>): INode[] {
|
||||
return (scripts || [])
|
||||
.map((script) => convertScriptToNode(script));
|
||||
}
|
||||
|
||||
function addCategories(categories: ReadonlyArray<ICategory>, nodes: INode[]): INode[] {
|
||||
if (!categories || categories.length === 0) {
|
||||
return nodes;
|
||||
}
|
||||
for (const category of categories) {
|
||||
const subCategoryNodes = parseCategoryRecursively(category);
|
||||
nodes.push(convertCategoryToNode(category, subCategoryNodes));
|
||||
}
|
||||
return nodes;
|
||||
function createCategoryNodes(categories: ReadonlyArray<ICategory>): INode[] {
|
||||
return (categories || [])
|
||||
.map((category) => ({ category, children: parseCategoryRecursively(category) }))
|
||||
.map((data) => convertCategoryToNode(data.category, data.children));
|
||||
}
|
||||
|
||||
function convertCategoryToNode(
|
||||
|
||||
@@ -25,7 +25,7 @@ function testExpectedInstanceTypes<T>(
|
||||
) {
|
||||
describe('create returns expected instances', () => {
|
||||
// arrange
|
||||
for (const language of Array.from(expectedTypes.keys())) {
|
||||
for (const language of expectedTypes.keys()) {
|
||||
it(ScriptingLanguage[language], () => {
|
||||
// act
|
||||
const expected = expectedTypes.get(language);
|
||||
|
||||
@@ -197,7 +197,7 @@ class UserScriptGeneratorMock implements IUserScriptGenerator {
|
||||
selectedScripts: readonly SelectedScript[],
|
||||
scriptingDefinition: IScriptingDefinition,
|
||||
): IUserScript {
|
||||
for (const [parameters, result] of Array.from(this.prePlanned)) {
|
||||
for (const [parameters, result] of this.prePlanned) {
|
||||
if (selectedScripts === parameters.scripts
|
||||
&& scriptingDefinition === parameters.definition) {
|
||||
return result;
|
||||
|
||||
@@ -13,16 +13,23 @@ describe('CodeChangedEvent', () => {
|
||||
it('throws when code position is out of range', () => {
|
||||
// arrange
|
||||
const code = 'singleline code';
|
||||
const nonExistingLine1 = 2;
|
||||
const nonExistingLine2 = 31;
|
||||
const newScripts = new Map<SelectedScript, ICodePosition>([
|
||||
[new SelectedScriptStub('1'), new CodePosition(0, 2 /* nonexisting line */)],
|
||||
[new SelectedScriptStub('1'), new CodePosition(0, nonExistingLine1)],
|
||||
[new SelectedScriptStub('2'), new CodePosition(0, nonExistingLine2)],
|
||||
]);
|
||||
// act
|
||||
const act = () => new CodeChangedEventBuilder()
|
||||
let errorText = '';
|
||||
try {
|
||||
new CodeChangedEventBuilder()
|
||||
.withCode(code)
|
||||
.withNewScripts(newScripts)
|
||||
.build();
|
||||
} catch (error) { errorText = error.message; }
|
||||
// assert
|
||||
expect(act).to.throw();
|
||||
expect(errorText).to.include(nonExistingLine1);
|
||||
expect(errorText).to.include(nonExistingLine2);
|
||||
});
|
||||
describe('does not throw with valid code position', () => {
|
||||
// arrange
|
||||
|
||||
@@ -151,6 +151,14 @@ describe('ExpressionsCompiler', () => {
|
||||
.withArgument('parameter2', 'value'),
|
||||
expectedError: 'parameter value(s) not provided for: "parameter1", "parameter3" but used in code',
|
||||
},
|
||||
{
|
||||
name: 'parameter names are not repeated in error message',
|
||||
expressions: [
|
||||
new ExpressionStub().withParameterNames(['parameter1', 'parameter1', 'parameter2', 'parameter2'], false),
|
||||
],
|
||||
args: new FunctionCallArgumentCollectionStub(),
|
||||
expectedError: 'parameter value(s) not provided for: "parameter1", "parameter2" but used in code',
|
||||
},
|
||||
];
|
||||
for (const testCase of testCases) {
|
||||
it(testCase.name, () => {
|
||||
|
||||
@@ -31,6 +31,31 @@ describe('RegexParser', () => {
|
||||
});
|
||||
}
|
||||
});
|
||||
it('throws when position is invalid', () => {
|
||||
// arrange
|
||||
const regexMatchingEmpty = /^/gm; /* expressions cannot be empty */
|
||||
const code = 'unimportant';
|
||||
const expectedErrorParts = [
|
||||
`[${RegexParserConcrete.constructor.name}]`,
|
||||
'invalid script position',
|
||||
`Regex: ${regexMatchingEmpty}`,
|
||||
`Code: ${code}`,
|
||||
];
|
||||
const sut = new RegexParserConcrete(regexMatchingEmpty);
|
||||
// act
|
||||
let error: string;
|
||||
try {
|
||||
sut.findExpressions(code);
|
||||
} catch (err) {
|
||||
error = err.message;
|
||||
}
|
||||
// assert
|
||||
expect(
|
||||
expectedErrorParts.every((part) => error.includes(part)),
|
||||
`Expected parts: ${expectedErrorParts.join(', ')}`
|
||||
+ `Actual error: ${error}`,
|
||||
);
|
||||
});
|
||||
describe('matches regex as expected', () => {
|
||||
// arrange
|
||||
const testCases = [
|
||||
|
||||
@@ -70,7 +70,7 @@ describe('FunctionCallCompiler', () => {
|
||||
},
|
||||
{
|
||||
name: 'provided: an unexpected parameter, when: none required',
|
||||
functionParameters: undefined,
|
||||
functionParameters: [],
|
||||
callParameters: ['unexpected-call-parameter'],
|
||||
expectedError:
|
||||
`Function "${functionName}" has unexpected parameter(s) provided: "unexpected-call-parameter"`
|
||||
@@ -90,10 +90,10 @@ describe('FunctionCallCompiler', () => {
|
||||
const func = new SharedFunctionStub(FunctionBodyType.Code)
|
||||
.withName('test-function-name')
|
||||
.withParameterNames(...testCase.functionParameters);
|
||||
let params: FunctionCallParametersData = {};
|
||||
for (const parameter of testCase.callParameters) {
|
||||
params = { ...params, [parameter]: 'defined-parameter-value ' };
|
||||
}
|
||||
const params = testCase.callParameters
|
||||
.reduce((result, parameter) => {
|
||||
return { ...result, [parameter]: 'defined-parameter-value ' };
|
||||
}, {} as FunctionCallParametersData);
|
||||
const call = new FunctionCallStub()
|
||||
.withFunctionName(func.name)
|
||||
.withArguments(params);
|
||||
|
||||
@@ -49,15 +49,11 @@ async function findBadLineNumbers(fileContent: string): Promise<number[]> {
|
||||
|
||||
function findLineNumbersEndingWith(content: string, ending: string): number[] {
|
||||
sanityCheck(content, ending);
|
||||
const lines = content.split(/\r\n|\r|\n/);
|
||||
const results = new Array<number>();
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (line.trim().endsWith(ending)) {
|
||||
results.push((i + 1 /* first line is 1 not 0 */));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
return content
|
||||
.split(/\r\n|\r|\n/)
|
||||
.map((line, index) => ({ text: line, index }))
|
||||
.filter((line) => line.text.trim().endsWith(ending))
|
||||
.map((line) => line.index + 1 /* first line is 1, not 0 */);
|
||||
}
|
||||
|
||||
function sanityCheck(content: string, ending: string): void {
|
||||
|
||||
@@ -121,15 +121,18 @@ describe('CategoryCollection', () => {
|
||||
expect(construct).to.throw('must consist of at least one script');
|
||||
});
|
||||
describe('cannot construct without any recommended scripts', () => {
|
||||
describe('single missing', () => {
|
||||
// arrange
|
||||
const recommendationLevels = getEnumValues(RecommendationLevel);
|
||||
for (const missingLevel of recommendationLevels) {
|
||||
it(`when "${RecommendationLevel[missingLevel]}" is missing`, () => {
|
||||
const expectedError = `none of the scripts are recommended as ${RecommendationLevel[missingLevel]}`;
|
||||
const expectedError = `none of the scripts are recommended as "${RecommendationLevel[missingLevel]}".`;
|
||||
const otherLevels = recommendationLevels.filter((level) => level !== missingLevel);
|
||||
const categories = otherLevels.map(
|
||||
(level, index) => new CategoryStub(index)
|
||||
.withScript(new ScriptStub(`Script${index}`).withLevel(level)),
|
||||
.withScript(
|
||||
new ScriptStub(`Script${index}`).withLevel(level),
|
||||
),
|
||||
);
|
||||
// act
|
||||
const construct = () => new CategoryCollectionBuilder()
|
||||
@@ -140,6 +143,24 @@ describe('CategoryCollection', () => {
|
||||
});
|
||||
}
|
||||
});
|
||||
it('multiple are missing', () => {
|
||||
// arrange
|
||||
const expectedError = 'none of the scripts are recommended as '
|
||||
+ `"${RecommendationLevel[RecommendationLevel.Standard]}, "${RecommendationLevel[RecommendationLevel.Strict]}".`;
|
||||
const categories = [
|
||||
new CategoryStub(0)
|
||||
.withScript(
|
||||
new ScriptStub(`Script${0}`).withLevel(undefined),
|
||||
),
|
||||
];
|
||||
// act
|
||||
const construct = () => new CategoryCollectionBuilder()
|
||||
.withActions(categories)
|
||||
.construct();
|
||||
// assert
|
||||
expect(construct).to.throw(expectedError);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('totalScripts', () => {
|
||||
it('returns total of initial scripts', () => {
|
||||
|
||||
@@ -61,15 +61,14 @@ describe('ScriptCode', () => {
|
||||
},
|
||||
];
|
||||
// act
|
||||
const actions = [];
|
||||
for (const testCase of testCases) {
|
||||
actions.push(...[
|
||||
const actions = testCases.flatMap((testCase) => ([
|
||||
{
|
||||
act: () => new ScriptCodeBuilder()
|
||||
.withExecute(testCase.code)
|
||||
.build(),
|
||||
testName: `execute: ${testCase.testName}`,
|
||||
expectedMessage: testCase.expectedMessage,
|
||||
code: testCase.code,
|
||||
},
|
||||
{
|
||||
act: () => new ScriptCodeBuilder()
|
||||
@@ -77,9 +76,9 @@ describe('ScriptCode', () => {
|
||||
.build(),
|
||||
testName: `revert: ${testCase.testName}`,
|
||||
expectedMessage: `(revert): ${testCase.expectedMessage}`,
|
||||
code: testCase.code,
|
||||
},
|
||||
]);
|
||||
}
|
||||
]));
|
||||
// assert
|
||||
for (const action of actions) {
|
||||
it(action.testName, () => {
|
||||
@@ -115,9 +114,7 @@ describe('ScriptCode', () => {
|
||||
},
|
||||
];
|
||||
// act
|
||||
const actions = [];
|
||||
for (const testCase of testCases) {
|
||||
actions.push(...[
|
||||
const actions = testCases.flatMap((testCase) => ([
|
||||
{
|
||||
testName: `execute: ${testCase.testName}`,
|
||||
act: () => new ScriptCodeBuilder()
|
||||
@@ -134,8 +131,7 @@ describe('ScriptCode', () => {
|
||||
.build(),
|
||||
expect: (sut: IScriptCode) => sut.revert === testCase.code,
|
||||
},
|
||||
]);
|
||||
}
|
||||
]));
|
||||
// assert
|
||||
for (const action of actions) {
|
||||
it(action.testName, () => {
|
||||
|
||||
@@ -39,7 +39,7 @@ describe('ScriptingDefinition', () => {
|
||||
[ScriptingLanguage.batchfile, 'bat'],
|
||||
[ScriptingLanguage.shellscript, 'sh'],
|
||||
]);
|
||||
Array.from(testCases.entries()).forEach((test) => {
|
||||
for (const test of testCases.entries()) {
|
||||
const language = test[0];
|
||||
const expectedExtension = test[1];
|
||||
it(`${ScriptingLanguage[language]} has ${expectedExtension}`, () => {
|
||||
@@ -50,7 +50,7 @@ describe('ScriptingDefinition', () => {
|
||||
// assert
|
||||
expect(sut.fileExtension, expectedExtension);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
describe('startCode', () => {
|
||||
|
||||
@@ -52,14 +52,12 @@ class SchedulerMock {
|
||||
|
||||
public tickNext(ms: number) {
|
||||
const newTime = this.currentTime + ms;
|
||||
let newActions = this.scheduledActions;
|
||||
for (const action of this.scheduledActions) {
|
||||
if (newTime >= action.time) {
|
||||
newActions = newActions.filter((a) => a !== action);
|
||||
const dueActions = this.scheduledActions
|
||||
.filter((action) => newTime >= action.time);
|
||||
for (const action of dueActions) {
|
||||
action.action();
|
||||
}
|
||||
}
|
||||
this.scheduledActions = newActions;
|
||||
this.scheduledActions = this.scheduledActions.filter((action) => !dueActions.includes(action));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,6 @@ describe('ScriptNodeParser', () => {
|
||||
expectSameScript(nodes[2], scripts[2]);
|
||||
});
|
||||
});
|
||||
|
||||
it('parseAllCategories parses as expected', () => {
|
||||
// arrange
|
||||
const collection = new CategoryCollectionStub()
|
||||
|
||||
@@ -61,46 +61,27 @@ export class CategoryCollectionStub implements ICategoryCollection {
|
||||
}
|
||||
|
||||
public getAllScripts(): ReadonlyArray<IScript> {
|
||||
const scripts = [];
|
||||
for (const category of this.actions) {
|
||||
const categoryScripts = getScriptsRecursively(category);
|
||||
scripts.push(...categoryScripts);
|
||||
}
|
||||
return scripts;
|
||||
return this.actions.flatMap((category) => getScriptsRecursively(category));
|
||||
}
|
||||
|
||||
public getAllCategories(): ReadonlyArray<ICategory> {
|
||||
const categories = [];
|
||||
categories.push(...this.actions);
|
||||
for (const category of this.actions) {
|
||||
const subCategories = getSubCategoriesRecursively(category);
|
||||
categories.push(...subCategories);
|
||||
}
|
||||
return categories;
|
||||
return this.actions.flatMap(
|
||||
(category) => [category, ...getSubCategoriesRecursively(category)],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function getSubCategoriesRecursively(category: ICategory): ReadonlyArray<ICategory> {
|
||||
const subCategories = [];
|
||||
if (category.subCategories) {
|
||||
for (const subCategory of category.subCategories) {
|
||||
subCategories.push(subCategory);
|
||||
subCategories.push(...getSubCategoriesRecursively(subCategory));
|
||||
}
|
||||
}
|
||||
return subCategories;
|
||||
return (category.subCategories || []).flatMap(
|
||||
(subCategory) => [subCategory, ...getSubCategoriesRecursively(subCategory)],
|
||||
);
|
||||
}
|
||||
|
||||
function getScriptsRecursively(category: ICategory): ReadonlyArray<IScript> {
|
||||
const categoryScripts = [];
|
||||
if (category.scripts) {
|
||||
categoryScripts.push(...category.scripts);
|
||||
}
|
||||
if (category.subCategories) {
|
||||
for (const subCategory of category.subCategories) {
|
||||
const subCategoryScripts = getScriptsRecursively(subCategory);
|
||||
categoryScripts.push(...subCategoryScripts);
|
||||
}
|
||||
}
|
||||
return categoryScripts;
|
||||
return [
|
||||
...(category.scripts || []),
|
||||
...(category.subCategories || []).flatMap(
|
||||
(subCategory) => getScriptsRecursively(subCategory),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -27,10 +27,9 @@ export class CategoryStub extends BaseEntity<number> implements ICategory {
|
||||
}
|
||||
|
||||
public withScriptIds(...scriptIds: string[]): CategoryStub {
|
||||
for (const scriptId of scriptIds) {
|
||||
this.withScript(new ScriptStub(scriptId));
|
||||
}
|
||||
return this;
|
||||
return this.withScripts(
|
||||
...scriptIds.map((id) => new ScriptStub(id)),
|
||||
);
|
||||
}
|
||||
|
||||
public withScripts(...scripts: IScript[]): CategoryStub {
|
||||
|
||||
@@ -58,12 +58,9 @@ function deepEqual(
|
||||
if (!scrambledEqual(expectedParameterNames, actualParameterNames)) {
|
||||
return false;
|
||||
}
|
||||
for (const parameterName of expectedParameterNames) {
|
||||
return expectedParameterNames.every((parameterName) => {
|
||||
const expectedValue = expected.getArgument(parameterName).argumentValue;
|
||||
const actualValue = actual.getArgument(parameterName).argumentValue;
|
||||
if (expectedValue !== actualValue) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return expectedValue === actualValue;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -14,9 +14,8 @@ export class FunctionCallArgumentCollectionStub implements IFunctionCallArgument
|
||||
}
|
||||
|
||||
public withArguments(args: { readonly [index: string]: string }) {
|
||||
for (const parameterName of Object.keys(args)) {
|
||||
const parameterValue = args[parameterName];
|
||||
this.withArgument(parameterName, parameterValue);
|
||||
for (const [name, value] of Object.entries(args)) {
|
||||
this.withArgument(name, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export class ScriptStub extends BaseEntity<string> implements IScript {
|
||||
|
||||
public readonly documentationUrls = new Array<string>();
|
||||
|
||||
public level = RecommendationLevel.Standard;
|
||||
public level? = RecommendationLevel.Standard;
|
||||
|
||||
constructor(public readonly id: string) {
|
||||
super(id);
|
||||
@@ -23,7 +23,7 @@ export class ScriptStub extends BaseEntity<string> implements IScript {
|
||||
return Boolean(this.code.revert);
|
||||
}
|
||||
|
||||
public withLevel(value: RecommendationLevel): ScriptStub {
|
||||
public withLevel(value?: RecommendationLevel): ScriptStub {
|
||||
this.level = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"module": "esnext",
|
||||
"jsx": "preserve",
|
||||
"importHelpers": true,
|
||||
"downlevelIteration": true,
|
||||
"moduleResolution": "node",
|
||||
"experimentalDecorators": true,
|
||||
"esModuleInterop": true,
|
||||
|
||||
Reference in New Issue
Block a user