@chix/iobox

Input/Output iobox

Usage no npm install needed!

<script type="module">
  import chixIobox from 'https://cdn.skypack.dev/@chix/iobox';
</script>

README

IO Box

Provides a simple semi protected IO sandbox.

It can also be use to serve as function generator for vm sandbox.

It wraps a function with the specified input arguments and returns the specified output, where output must be one of the input arguments.

The idea here is that you save the definition of the function along with the generated function.

So you always know what is the input & the output.

The semi-protection is accomplished by pushing global variables names at end of the input array.

e.g. function(input, output) is what you really use, but you also push global vars there:

function(input, output, window, document, whatever, console, unused)

Those will then end up being undefined.

It's meant to enforce a certain kind of api within the function body.

Example

var IOBox = require('iobox');

var ins  = ['input','output']; // input specification
var outs = ['output'];         // output specification, must be one of the inputs.

var io = new IOBox('my-func', ins, outs);

Compile the function to return output as an Array:


io.compile('output.out = input.in');

console.log('Output as array:', io.toString());

Output as array:

function (input,output) {

  var r = function() {
    output.out = input.in; // function body handling input & output
  }();
  return [output, r];       // Output as Array
}

Compile the function to return output as an Object:


io.compile('output.out = input.in', true);

console.log('Output as object:', io.toString());

Output as object:

function (input,output) {

  var r = function() {
    output.out = input.in; // function body handling input & output
  };

  return {
    output: output  // Output as Object
    return: r       // original return
  };
}

Run with output as Array:

console.log(io.run());

['Hi', undefined]

Run with output as Object:

console.log(io.run());

{ output: { out: 'Hi' }, return: undefined }

io.toString() can be used to save the function for later use.