首页
/ 使用ts-morph实现面向对象到数据导向的代码转换

使用ts-morph实现面向对象到数据导向的代码转换

2025-06-07 21:11:08作者:田桥桑Industrious

在JavaScript/TypeScript开发中,我们经常需要在面向对象编程(OOP)和数据导向编程(DOP)两种范式之间进行选择。本文将通过ts-morph工具,展示如何将传统的面向对象风格的Vec2类转换为数据导向风格的数组操作。

背景介绍

Vec2类通常表示二维向量,传统面向对象实现会封装x、y属性和相关操作方法。而数据导向风格则倾向于使用纯数组表示向量,配合静态方法进行操作。两种方式各有优劣:

  • 面向对象:代码组织清晰,易于理解
  • 数据导向:性能更优,更适合大规模数据处理

转换方案实现

1. 构造函数转换

首先将new Vec2(x, y)调用转换为工厂函数形式Vec2.create(x, y)

const newExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.NewExpression);
newExpressions.forEach((newExpression) => {
  const className = newExpression.getExpression().getText();
  if (className === "Vec2") {
    const args = newExpression.getArguments().map(arg => arg.getText()).join(", ");
    newExpression.replaceWithText(`Vec2.create(${args})`);
  }
});

2. 属性访问转换

将对象属性访问.x.y转换为数组索引[0][1]

const propertyAccesses = sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression);
propertyAccesses.forEach((propertyAccess) => {
  const propertyName = propertyAccess.getName();
  const expression = propertyAccess.getExpression();
  const type = expression.getType().getText();

  if ((propertyName === "x" || propertyName === "y") && 
      (type.includes("Vec2") || type.includes("Vec2Value"))) {
    const index = propertyName === "x" ? 0 : 1;
    propertyAccess.replaceWithText(`${expression.getText()}[${index}]`);
  }
});

3. 方法调用转换

将实例方法调用转换为静态方法调用:

const className = 'Vec2Value';
const methodNames = ['add', 'cross', 'sub'];

methodNames.forEach(methodName => {
  const memberMethod = classDeclaration.getInstanceMethod(methodName);
  if (!memberMethod) return;

  const references = memberMethod.findReferences();
  references.forEach(ref => {
    ref.getReferences().forEach(reference => {
      const refNode = reference.getNode();
      if (Node.isPropertyAccessExpression(refNode.getParent())) {
        const propertyAccess = refNode.getParent();
        const callExpression = propertyAccess.getParentIfKind(SyntaxKind.CallExpression);

        if (callExpression) {
          const instance = propertyAccess.getExpression().getText();
          const args = callExpression.getArguments().map(arg => arg.getText());
          callExpression.replaceWithText(
            `${className}.${methodName}(${[instance, ...args].join(", ")})`
          );
        }
      }
    });
  });
});

转换效果对比

转换前(面向对象风格):

const a = new Vec2(100, 50);
const b = new Vec2(20, 30);
a.add(b);
console.log(a.x, b.x);  // 120, 80

转换后(数据导向风格):

const a = Vec2.create(100, 50);
const b = Vec2.create(20, 30);
const out = Vec2.create();
Vec2.add(out, a, b);
console.log(out[0], out[1]);  // 120, 80

技术要点解析

  1. AST操作:ts-morph通过操作抽象语法树(AST)实现代码转换,比正则表达式更可靠
  2. 类型安全:在属性访问转换时检查类型,确保只转换Vec2相关属性
  3. 引用查找:方法转换时通过findReferences查找所有调用点
  4. 上下文感知:区分属性访问和方法调用场景,进行针对性转换

实际应用建议

  1. 增量转换:可以先转换部分代码,逐步验证效果
  2. 测试保障:转换前后应保持单元测试通过
  3. 性能考量:数据导向风格在游戏开发、图形处理等场景性能优势明显
  4. 代码可读性:可考虑保留两种风格,通过文档说明适用场景

通过ts-morph实现的这种转换,可以帮助开发者在保持功能不变的前提下,灵活调整代码范式以适应不同场景需求。

登录后查看全文
热门项目推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
136
214
leetcodeleetcode
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
51
15
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
645
434
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
98
152
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
300
1.03 K
MateChatMateChat
前端智能化场景解决方案UI库,轻松构建你的AI应用,我们将持续完善更新,欢迎你的使用与建议。 官网地址:https://matechat.gitcode.com
697
96
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
505
42
RuoYi-Cloud-Vue3RuoYi-Cloud-Vue3
🎉 基于Spring Boot、Spring Cloud & Alibaba、Vue3 & Vite、Element Plus的分布式前后端分离微服务架构权限管理系统
Vue
115
81
carboncarbon
轻量级、语义化、对开发者友好的 golang 时间处理库
Go
8
2
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
109
255