Example: Run JavaScript in the Command Window

The V8 JavaScript engine is built into Manifold so we can always run JavaScript within the Command window.  In the screen shots below we have closed the Project pane to enable more compact illustrations.   For tips on editing the text of scripts, see the Editing Queries, Scripts and Comments topic.

 

eg_cmdwinjs01_01.png

 

 Choose View - New Command Window - JavaScript to open a Command window for JavaScript.

 

eg_cmdwinjs01_02.png

 

In the command pane we enter a classic example of recursion used to compute the factorial of a number:

 

function factorial(n) {

  return n === 1 ? 1 : n * factorial(n - 1);

}

 

eg_cmdwinjs01_03.png

 

JavaScript is recursive so we can utilize the power of recursion to write a simple and elegant factorial function.

 

factorial(6);

 

We then call the function to calculate the factorial of the number 6, the factorial being 6 * 5 * 4 * 3 * 2 * 1.

 

eg_cmdwinjs01_04.png

 

We push the ! run button to execute the script.  

 

eg_cmdwinjs01_05.png

 

The Log window reports both the script we ran as well as the result, in this case 720, the factorial of 6.

 

Let's create a script that uses a message box.    We will compute a Fibonacci number using, once again, recursion.

 

function fib(a) {

  if (a < 1)

    return 0;

  if (a == 1)

    return 1;

  return fib(a-1) + fib(a-2);

}

 

Manifold.Application.MessageBox('fib(7)=' + fib(7));

 

We enter the above script into the command pane and then press the ! button to run the script.

 

eg_cmdwinjs01_06.png

 

As expected, the result is a message box with the seventh Fibonacci number, 13.

 

eg_cmdwinjs01_07.png

 

Manifold has the V8 engine, a very fast Javascript engine, built in so that Javascript is always available..  Other than being an exceptionally fast engine V8 is regular Javascript so almost any Javascript code will work.

 

Notes

You can't make this stuff up -  An actual screenshot just after pushing the search button...

 

il_google_recurs.png

See Also

Tables

 

Queries

 

Editing Queries, Scripts and Comments

 

Command Window

 

Example: Create and Run a Query -  See how the different parts of a command window operate when creating and running SQL queries.   Includes use of the Log tab as well as the ?expression and !fullfetch commands.

 

Example: Refer to a Table within a Data Source -  Within a query, how to refer to a table that is in a data source.

 

Example: Switching between Manifold and Native Query Engines - How to use the !manifold and !native commands to switch a query in the Command window from use the Manifold query engine to whatever query engine is provided by a data source.

 

Example: Automatically Generating CREATE Queries - How to use the Command window to automatically generate SQL in the form of CREATE queries that create a desired component.