项目作者: julien-moreau

项目描述 :
Groovy to JS
高级语言: TypeScript
项目地址: git://github.com/julien-moreau/groovy-to-js.git
创建时间: 2017-09-14T19:07:34Z
项目社区:https://github.com/julien-moreau/groovy-to-js

开源协议:

下载


" class="reference-link">groovy-to-js Build status

Groovy to JS simply tries to convert a Groovy code to JavaScript code.

Features

  • Check types to call methods (subtract, add, multiply, etc.) on arrays
  • Supports [number].times { … }
  • Supports simple closures
  • Supports ranges ([number]..[number], [identifier]..[number], etc.)
  • Supports triple quotes (simple & double) strings

Roadmap

  • Test on advanced code
  • Provide more functions to dictionnary

Not supported

  • Class definitions
  • array[index < 0]

Using Groovy-To-JS

  1. import groovy_to_js from 'groovy-to-js';
  2. const js = groovy_to_js(my_groovy_code_as_string);

Using the converter

  1. // Import lib
  2. import Analyser from 'groovy-to-js';
  3. const groovy = `
  4. def arr = [1, 2, 3];
  5. arr -= 1;
  6. def map = [
  7. a: 0,
  8. b: [1, 2, 3]
  9. ];
  10. map.a = map.b.size();
  11. `;
  12. const js = Analyser.convert(groovy);
  13. console.log(js);
  14. // Gives:
  15. /*
  16. var arr = [1, 2, 3];
  17. arr = subtract(arr, 1);
  18. var map = {
  19. a: 0,
  20. b: [1, 2, 3]
  21. };
  22. map.a = map.b.length
  23. */

Giving a scope to check types

Converting a groovy script would require to know the base scope.

Given this scope:

  1. const scope = {
  2. member: [1, 2, 3]
  3. };

And this groovy script

  1. const groovy = `
  2. return myObject.member - 1;
  3. `;

Would return:

  1. `return myObject.member - 1;`;

The problem is, member is an array, so the output should be:

  1. `return subtract(myObject.member, 1);

To prevent this, just build a base scope, that’s all!

Example:

  1. // Import scope
  2. import { Analyser, Variable } from 'groovy-to-js';
  3. const scope = Variable.buildFrom({
  4. member: [1, 2, 3]
  5. });
  6. const groovy = `
  7. return myObject.member - 1;
  8. `;
  9. const js = Analyser.convert(groovy, scope);
  10. console.log(js);
  11. // Gives:
  12. /*
  13. return subtract(myObject.member, 1);
  14. */

Requiring groovy functions

These are called augmentations that you can import like:

  1. import { augmentations } from 'groovy-to-js';
  2. const a = [1, 2, 3];
  3. const b = 2;
  4. const c = [2];
  5. console.log(augmentations.subtract(a, b)); // [1, 3]
  6. console.log(augmentations.subtract(a, c)); // [1, 3]
  7. console.log(augmentations.add(a, b)); // [1, 2, 3, 2];
  8. console.log(augmentations.add(a, c)); // [1, 2, 3, 2];
  9. console.log(augmentations.multiply(a, b)); // [1, 2, 3, 1, 2, 3];
  10. console.log(augmentations.multiply(a, c)); // [1, 2, 3, 1, 2, 3];
  11. console.log(augmentations.range(2, 5)); // [2, 3, 4, 5]
  12. augmentations.times(3, (it) => {
  13. console.log(it);
  14. }); // 3 -> 3 -> 3