dsherret / dsherret/ts-morph

Reordering properties in an ObjectLiteralExpression

Open
#1,178 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
TypeScript
Stars
6.2k
Forks
238
Avg merge
2m
Merged PRs (30d)
1

Description

**Is your feature request related to a problem? Please describe.**

I am developing a program that reads a TypeScript source file that contains an object literal defining tokenized keys and translations for an application, in this structure:

```js
const resources = {
accountInformation: "Información de la cuenta",
cancelMySubscription: "Cancelar mi suscripción",
checkOutFaq: "Echa un vistazo a nuestras preguntas frecuentes",
subscriptionDetails: "Detalles de suscripción",
teamManagement: "Gestión de equipos",
};
```

For organizational purposes, it's nice to keep this file alphabetized by the object's keys. Right now, my code that does this is essentially...

```ts
const sortPropertyAssignments = (
literal: ObjectLiteralExpression
): ObjectLiteralExpression => {
const existingProperties = getPropertyAssignments(literal);
const sortedProperties = sortPropertiesByName(
existingProperties
).map((property) => property.getStructure());
existingProperties.forEach((existing) => existing.remove());
literal.addPropertyAssignments(sortedProperties);
return literal;
};
```

This is sufficient for smaller objects, but when the object is several hundred assignments, it takes a bit to save out the changes (3-4 seconds).

I originally had similar code for removing and re-adding `InterfaceDeclaration` members, which was just as slow, but I stumbled upon the `setOrder` function which was much faster. However, I am not aware of a similar API for the `ObjectLiteralExpression` node.

**Describe the solution you'd like**

Having an equivalent `setOrder` function for the `ObjectLiteralExpression` node would be awesome - or really, any sort of 'move'/'sort' ability out-of-the-box. If I'm totally missing some part of the API to accomplish this, I'd love to know what a better solution would be!

Contributor guide

Open the contributing guide

Research direction

Start by examining the ObjectLiteralExpression API and the existing InterfaceDeclaration setOrder behavior described in the issue. Compare it with the remove-and-readd approach shown; done means an ordering operation for object-literal properties that avoids that slowdown while preserving the requested order.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.