How to minify dynamic generated code?

Posted on
  • Some times you need code that is dependent on parameter. Like having one up to five analog reads depense on your device. Having it readable eats up lots of space.

    Is there a way to minify Sting module?

    count = 3;
    name = 'analogRead';
    var APINS = [ D28, D3, D4, D30, D29 ];
    var analogRead = {};
    
    var buildModule = (c) =>{
      var module = "", i = 0;
      module = `exports = function (interval) {
      var a0 = 0
        , a1 = 0
        , a2 = 0
        , a3 = 0
        , a4 = 0
      ;
      setInterval(() => {
    `;
      for (i = 0; i < count; i++) {
        module += '    a'+i+' = analogRead('+APINS[i]+');\n';
      }
      module +=`    print(`;
          module += ' a'+0+'.toFixed(3)\n';
      for (i =1; i < count; i++) {
        module += '         , a'+i+'.toFixed(3)\n';
      }
      module +=`    );
       }, interval);
    }`;
    
      require('Storage').write(name, module);
      print(module);
    };
    
    buildModule(count);
    analogRead = require(name);
    

    output

    exports = function (interval) {
      var a0 = 0
          , a1 = 0
          , a2 = 0
          , a3 = 0
          , a4 = 0
      ;
        setInterval(() => {
          a0 = analogRead(D28);
          a1 = analogRead(D3);
          a2 = analogRead(D4);
          print( a0.toFixed(3)
               , a1.toFixed(3)
               , a2.toFixed(3)
          );
       }, interval);
    
  • Yes, there is - just ensure you have the "ram" keyword at the front of the function and Espruino will pretokenise it and remove whitespace. It won't exactly minify (renaming vars) because there is no minifier in Espruino, but it will really help.

    Either that or for the kind of code you have there in the interval you could even add "jit" to it to compile it to native code.

  • Not sure if I understand you correctly. The code is in String module and get loaded during runtime.
    with analogRead = require(name);

  • You just make sure that in your code you change setInterval(() => { to setInterval(() => {"ram" and when the module is loaded that function will be minified.

    But it won't be written to Storage as minified. If that really is your code, I'd consider maybe just not writing the module to storage at all, but just using eval to evaluate the string then and there to create the minified function in RAM

  • Many thanks, minify to storage is not important. Wow never used "ram" before, sounds helpfull. Nice hint using eval will consider this too.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

How to minify dynamic generated code?

Posted by Avatar for MaBe @MaBe

Actions