Skip to content

Instantly share code, notes, and snippets.

@hi-ogawa
Last active January 12, 2024 11:27
Show Gist options
  • Save hi-ogawa/3c96fe5693745354a54af13a1eec4c15 to your computer and use it in GitHub Desktop.
Save hi-ogawa/3c96fe5693745354a54af13a1eec4c15 to your computer and use it in GitHub Desktop.
jscodeshift example (object literal manipulation)
import type { API, FileInfo } from "jscodeshift";
//
// usage:
// npx jscodeshift --parser tsx --transform match-and-replace-object-literal.ts <files>
//
// { act: "SELL", prc: 0, dt?: null, ... } => { act: "LOSS", prc: 0, dt?: null, ... }
//
export default function transformer(file: FileInfo, api: API): string {
const j = api.jscodeshift;
const $j = j(file.source);
for (const path of $j.find(j.ObjectExpression).paths()) {
const act = j(path)
.find(j.ObjectProperty, { key: { type: "Identifier", name: "act" } })
.filter(
p =>
p.parentPath.parentPath === path &&
p.value.value.type === "StringLiteral" &&
p.value.value.value === "SELL"
);
const prc = j(path)
.find(j.ObjectProperty, { key: { type: "Identifier", name: "prc" } })
.filter(
p =>
p.parentPath.parentPath === path &&
p.value.value.type === "NumericLiteral" &&
p.value.value.value === 0
);
const dt = j(path)
.find(j.ObjectProperty, { key: { type: "Identifier", name: "dt" } })
.filter(p => p.parentPath.parentPath === path && p.value.value.type !== "NullLiteral");
if (act.length === 1 && prc.length === 1 && dt.length === 0) {
act.replaceWith(j.objectProperty(j.identifier("act"), j.stringLiteral("LOSS")));
}
}
return $j.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment