Skip to content

Commit

Permalink
Merge pull request #874 from acacode/reduce-use-of-lodash
Browse files Browse the repository at this point in the history
Reduce use of lodash
  • Loading branch information
smorimoto authored Aug 11, 2024
2 parents 7a7111b + a1b7136 commit 7b7e4f2
Show file tree
Hide file tree
Showing 30 changed files with 231 additions and 278 deletions.
4 changes: 2 additions & 2 deletions cli/execute.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,14 @@ const processArgs = (commands, args) => {

let allFlagKeys = [];

lodash.forEach(args, (arg, i) => {
args.forEach((arg, i) => {
if (error) return;

if (i === 0) {
command = commands[arg];

if (!command && !arg.startsWith("-")) {
const tip = didYouMean(arg, lodash.keys(commands));
const tip = didYouMean(arg, commands.keys());
error = `unknown command ${arg}${
tip ? `\n(Did you mean ${tip} ?)` : ""
}`;
Expand Down
10 changes: 6 additions & 4 deletions cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const cli = (input) => {
commands[command.name] = {
name: command.name,
description: `${command.description || ""}`,
options: lodash.compact(lodash.map(command.options, processOption)),
options: lodash.compact(command.options.map(processOption)),
};

if (addVersion) {
Expand Down Expand Up @@ -57,7 +57,7 @@ const cli = (input) => {
},
);

lodash.forEach(input.options, (option) => {
for (const option of input.options) {
const processed = processOption(option);

if (!processed) return;
Expand All @@ -68,7 +68,7 @@ const cli = (input) => {
}

commands[root_command].options.push(processed);
});
}

commands[root_command].options.unshift(
processOption({
Expand All @@ -86,7 +86,9 @@ const cli = (input) => {
}),
);

lodash.forEach(input.commands, addCommand);
for (const command of input.commands) {
addCommand(command);
}

return instance;
};
Expand Down
38 changes: 20 additions & 18 deletions cli/process-option.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,30 @@ const processFlags = (flags) => {
let value = null;
const isNoFlag = flags.includes("--no-");

lodash
.compact(lodash.split(flags, " ").map((str) => str.replace(/,/g, "")))
.forEach((str) => {
if (str.startsWith("-")) {
keys.push(str);
} else if (value === null) {
if (str.startsWith("{") || str.startsWith("[") || str.startsWith("<")) {
const rawValue = str.replace(/[{[<>}\].]/g, "");
const variadic = str.includes("...");
value = {
raw: str,
variadic,
name: rawValue,
formatter: optionFormatters[rawValue] || optionFormatters.string,
};
}
const strArr = lodash.compact(
flags.split(" ").map((str) => str.replace(/,/g, "")),
);

for (const str of strArr) {
if (str.startsWith("-")) {
keys.push(str);
} else if (value === null) {
if (str.startsWith("{") || str.startsWith("[") || str.startsWith("<")) {
const rawValue = str.replace(/[{[<>}\].]/g, "");
const variadic = str.includes("...");
value = {
raw: str,
variadic,
name: rawValue,
formatter: optionFormatters[rawValue] || optionFormatters.string,
};
}
});
}
}

const longestKey = keys.slice().sort((a, b) => b.length - a.length)[0];

if (!lodash.isEmpty(longestKey)) {
if (longestKey !== "") {
name = lodash.camelCase(
(isNoFlag ? longestKey.replace("--no-", "") : longestKey).replace(
/(--?)/,
Expand Down
3 changes: 1 addition & 2 deletions src/code-formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ class CodeFormatter {
)[0];

if (fileTextChanges?.textChanges.length) {
return lodash.reduceRight(
fileTextChanges.textChanges,
return fileTextChanges.textChanges.reduceRight(
(content, { span, newText }) =>
`${content.slice(0, span.start)}${newText}${content.slice(
span.start + span.length,
Expand Down
15 changes: 10 additions & 5 deletions src/code-gen-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ class CodeGenProcess {
const isDirPath = this.fileSystem.pathIsDir(this.config.output);

if (isDirPath) {
files.forEach((file) => {
for (const file of files) {
this.fileSystem.createFile({
path: this.config.output,
fileName: `${file.fileName}${file.fileExtension}`,
Expand All @@ -190,7 +190,7 @@ class CodeGenProcess {
`"${file.fileName}${file.fileExtension}"`,
`created in ${this.config.output}`,
);
});
}
}

return {
Expand Down Expand Up @@ -289,7 +289,12 @@ class CodeGenProcess {
rawTypeData,
)
: rawTypeData;
let { typeIdentifier, name: originalName, content, description } = typeData;
const {
typeIdentifier,
name: originalName,
content,
description,
} = typeData;
const name = this.typeNameFormatter.format(originalName);

if (name === null) return null;
Expand Down Expand Up @@ -560,11 +565,11 @@ class CodeGenProcess {

injectClassInstance = (key, value) => {
this[key] = value;
PATCHABLE_INSTANCES.forEach((instanceKey) => {
for (const instanceKey of PATCHABLE_INSTANCES) {
if (instanceKey !== key && key in this[instanceKey]) {
this[instanceKey][key] = value;
}
});
}
};
}

Expand Down
4 changes: 2 additions & 2 deletions src/commands/generate-templates/templates-gen-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class TemplatesGenProcess {
this.fileSystem.createDir(outputPath);
}

templates.forEach((template) => {
for (const template of templates) {
const templateName = this.fileSystem.cropExtension(template.name);
const templateEjsPath = path.resolve(outputPath, `${templateName}.ejs`);
const templateEtaPath = path.resolve(outputPath, `${templateName}.eta`);
Expand Down Expand Up @@ -94,7 +94,7 @@ class TemplatesGenProcess {
});
}
}
});
}

this.logger.success(
`source templates has been successfully created in "${outputPath}"`,
Expand Down
4 changes: 2 additions & 2 deletions src/configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,8 @@ class CodeGenConfig {
customTranslator;

Ts = {
Keyword: lodash.cloneDeep(TsKeyword),
CodeGenKeyword: lodash.cloneDeep(TsCodeGenKeyword),
Keyword: structuredClone(TsKeyword),
CodeGenKeyword: structuredClone(TsCodeGenKeyword),
/**
* $A[] or Array<$A>
*/
Expand Down
4 changes: 2 additions & 2 deletions src/schema-components-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ class SchemaComponentsMap {
* @returns {SchemaComponent[]}
*/
filter(...componentNames) {
return lodash.filter(this._data, (it) =>
return this._data.filter((it) =>
componentNames.some((componentName) =>
lodash.startsWith(it.$ref, `#/components/${componentName}`),
it.$ref.startsWith(`#/components/${componentName}`),
),
);
}
Expand Down
4 changes: 2 additions & 2 deletions src/schema-parser/base-schema-parsers/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class ArraySchemaParser extends MonoSchemaParser {
let contentType;
const { type, description, items } = this.schema || {};

if (lodash.isArray(items) && type === SCHEMA_TYPES.ARRAY) {
if (Array.isArray(items) && type === SCHEMA_TYPES.ARRAY) {
const tupleContent = [];
for (const item of items) {
tupleContent.push(
Expand All @@ -25,7 +25,7 @@ class ArraySchemaParser extends MonoSchemaParser {
}

return {
...(lodash.isObject(this.schema) ? this.schema : {}),
...(typeof this.schema === "object" ? this.schema : {}),
$schemaPath: this.schemaPath.slice(),
$parsedSchema: true,
schemaType: SCHEMA_TYPES.PRIMITIVE,
Expand Down
2 changes: 1 addition & 1 deletion src/schema-parser/base-schema-parsers/complex.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class ComplexSchemaParser extends MonoSchemaParser {
](this.schema);

return {
...(lodash.isObject(this.schema) ? this.schema : {}),
...(typeof this.schema === "object" ? this.schema : {}),
$schemaPath: this.schemaPath.slice(),
$parsedSchema: true,
schemaType: SCHEMA_TYPES.COMPLEX,
Expand Down
39 changes: 19 additions & 20 deletions src/schema-parser/base-schema-parsers/discriminator.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
);

return {
...(lodash.isObject(this.schema) ? this.schema : {}),
...(typeof this.schema === "object" ? this.schema : {}),
$schemaPath: this.schemaPath.slice(),
$parsedSchema: true,
schemaType: SCHEMA_TYPES.COMPLEX,
Expand Down Expand Up @@ -121,19 +121,19 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {

if (ableToCreateMappingType) {
return ts.TypeWithGeneric(mappingTypeName, [mappingUsageKey, content]);
} else {
return ts.ExpressionGroup(
ts.IntersectionType([
ts.ObjectWrapper(
ts.TypeField({
key: discriminator.propertyName,
value: mappingUsageKey,
}),
),
content,
]),
);
}

return ts.ExpressionGroup(
ts.IntersectionType([
ts.ObjectWrapper(
ts.TypeField({
key: discriminator.propertyName,
value: mappingUsageKey,
}),
),
content,
]),
);
};

for (const [mappingKey, schema] of mappingEntries) {
Expand Down Expand Up @@ -213,8 +213,8 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
const mappingRefSchema =
this.schemaUtils.getSchemaRefType(mappingSchema)?.rawTypeData;
if (mappingRefSchema) {
complexSchemaKeys.forEach((schemaKey) => {
if (lodash.isArray(mappingRefSchema[schemaKey])) {
for (const schemaKey of complexSchemaKeys) {
if (Array.isArray(mappingRefSchema[schemaKey])) {
mappingRefSchema[schemaKey] = mappingRefSchema[schemaKey].map(
(schema) => {
if (schema.$ref === refPath) {
Expand Down Expand Up @@ -251,7 +251,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
},
);
}
});
}
}
}
};
Expand All @@ -263,13 +263,12 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
this.schemaParser._complexSchemaParsers,
);
const schema = lodash.omit(
lodash.clone(noDiscriminatorSchema),
structuredClone(noDiscriminatorSchema),
complexSchemaKeys,
);
const schemaIsAny =
this.schemaParserFabric.getInlineParseContent(
lodash.cloneDeep(schema),
) === this.config.Ts.Keyword.Any;
this.schemaParserFabric.getInlineParseContent(structuredClone(schema)) ===
this.config.Ts.Keyword.Any;
const schemaIsEmpty = !lodash.keys(schema).length;

if (schemaIsEmpty || schemaIsAny) return null;
Expand Down
20 changes: 7 additions & 13 deletions src/schema-parser/base-schema-parsers/enum.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,34 +70,28 @@ class EnumSchemaParser extends MonoSchemaParser {
return this.config.Ts.NullValue(value);
}
if (
lodash.includes(
keyType,
this.schemaUtils.getSchemaType({ type: "number" }),
)
keyType.includes(this.schemaUtils.getSchemaType({ type: "number" }))
) {
return this.config.Ts.NumberValue(value);
}
if (
lodash.includes(
keyType,
this.schemaUtils.getSchemaType({ type: "boolean" }),
)
keyType.includes(this.schemaUtils.getSchemaType({ type: "boolean" }))
) {
return this.config.Ts.BooleanValue(value);
}

return this.config.Ts.StringValue(value);
};

if (lodash.isArray(enumNames) && lodash.size(enumNames)) {
content = lodash.map(enumNames, (enumName, index) => {
if (Array.isArray(enumNames) && lodash.size(enumNames)) {
content = enumNames.map((enumName, index) => {
const enumValue = lodash.get(this.schema.enum, index);
const formattedKey = this.formatEnumKey({
key: enumName,
value: enumValue,
});

if (this.config.enumNamesAsValues || lodash.isUndefined(enumValue)) {
if (this.config.enumNamesAsValues || enumValue === undefined) {
return {
key: formattedKey,
type: this.config.Ts.Keyword.String,
Expand All @@ -112,7 +106,7 @@ class EnumSchemaParser extends MonoSchemaParser {
};
});
} else {
content = lodash.map(this.schema.enum, (value) => {
content = this.schema.enum.map((value) => {
return {
key: this.formatEnumKey({ value }),
type: keyType,
Expand All @@ -122,7 +116,7 @@ class EnumSchemaParser extends MonoSchemaParser {
}

return {
...(lodash.isObject(this.schema) ? this.schema : {}),
...(typeof this.schema === "object" ? this.schema : {}),
$ref: $ref,
typeName: this.typeName || ($ref && refType.typeName) || null,
$parsedSchema: true,
Expand Down
9 changes: 4 additions & 5 deletions src/schema-parser/base-schema-parsers/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class ObjectSchemaParser extends MonoSchemaParser {
const contentProperties = this.getObjectSchemaContent(this.schema);

return {
...(lodash.isObject(this.schema) ? this.schema : {}),
...(typeof this.schema === "object" ? this.schema : {}),
$schemaPath: this.schemaPath.slice(),
$parsedSchema: true,
schemaType: SCHEMA_TYPES.OBJECT,
Expand All @@ -17,10 +17,9 @@ class ObjectSchemaParser extends MonoSchemaParser {
description: this.schemaFormatters.formatDescription(
this.schema.description,
),
allFieldsAreOptional: !lodash.some(
lodash.values(contentProperties),
(part) => part.isRequired,
),
allFieldsAreOptional: !contentProperties
.values()
.some((part) => part.isRequired),
content: contentProperties,
};
}
Expand Down
Loading

0 comments on commit 7b7e4f2

Please sign in to comment.