## App-Writer Code Snippets

App-Writer Code Snippets are a set of bits of code I use regularly for my own apps so may be useful for you. Just copy/paste into your own Javascript to quickly implement some core coding needs.

### A few inputs and outputs

The automatic app already has lines for reading in the variables from sliders, textboxes and so forth. And the readonly output boxes already have basic code in place with a dummy value, 10, implemented. Let's now do the most basic of app things which is to take those inputs, do a calculation and put the output, suitably formatted into the read-only text box. Assume that we have already read two inputs, alpha and beta, and we want to put their product into the box called OutVar

``````//This will work but the formatting is arbitrary
var alphabeta=alpha*beta \$('#OutVar').val(alphabeta)

//If you know you want it to 2 decimal places, this is great
\$('#OutVar').val(alphabeta.toFixed(2))

//This is great if you have a big possible range of outputs from 1000s to 0.0001s and want to ensure 2 significant figures
\$('#OutVar').val(alphabeta.toPrecision(2))``````

If the calculation depended on a Checkbox called chkDiv then the calculation would use the value already created in the app, chkDivIsChecked

``````var alphabeta
if (chkDivIsChecked)
{
alphabeta=alpha/beta
} else
{
alphabeta=alpha*beta
}``````

### Plotting a graph

Suppose we want to plot a graph of y=alpha.e-x/beta where x goes from 0 to 100 in N steps. We already have the graphing array, PPts1 defined and the code is already in place to plot this array. So all we have to do is fill it.

``````var i,x,y
for (i=0; i<=N; i++)
{
x=i*100/N
y=alpha*Math.exp(-x/beta)
PPts.push([x,y])
//The round brackets are a function, the square brackets are an array with two values
} ``````

### Fitting some data to a polynomial

We have two problems here. First we have to input the data, second we have to fit it - in this case to a polynomial, you can imagine fitting to other forms. Because of the safety aspects of Javascript it is not easy to casually access data from your local machine. Although I could describe some Ajax/JSON tricks, unless you were running under locahost on your development machine, in most browsers it wouldn't work. Instead we use the common trick of taking data from an input TextArea (a Textbox can only handle a single line, a TextArea handles multi-lines). So, somehow or other you have pasted some x,y data into a TextArea called DataIn. You've decided to separated the values via tabs (that's what I always use) but you can imagine the code with separations via commas or spaces. Reading the data is easy except for the fact that users tend to make mistakes in their data table, adding blank lines or unexpected column headers. So we have to have some elementary checks to avoid a Javascript error. Really good coders would handle this in a much better way - I'm using "scientists" coding which gets the job done well enough. Note that it is very common to find that the code checking for user errors is much larger than the code doing useful stuff.

``````//The data to fit get pushed into DataPairs and we have zero data points
var DataPairs=[],NData=0
var InData=\$(#'DataIn').val()

//Split the data into individual rows using \n as the code for new line
var Rows=InData.split("\n")
var i,Cols for(i=0;i<Rows.length;i++)
{
//Split on the tab symbol
Cols=Rows[i].split("\t")

//Look out for empty or over-filled lines
if (Cols.length==2)
{
//Make sure both are a valid number
if(!isNaN(Cols) && !isNaN(Cols))
{
//parseFloat ensures that the array is filled with number pairs, not strings
DataPairs.push([parseFloat(Cols),parseFloat(Cols)])

//We only increment the data counter when we've had a valid data pair
NData+=1
}
}
}
//Hooray, we now have our data, let's fit it
var Poly=3

//We want a 3rd degree polynomial
if(NData<Poly+1)
{
//Do something to abandon the fit without enough data
}
var TheFit = regression('polynomial', DataPairs, Poly)
//That's the fitting done!
//The parameters are TheFit.equation ... TheFit.equation and you do with them whatever you want.``````
Obviously you need the "regression" algorithm. I just used some excellent code found on GitHub, https://github.com/Tom-Alexander/regression-js. You might prefer something else. The code will be very similar.

The point is that coding scientists don't have to reinvent the wheel. There are lots of great resources in Javascript, ready to use. Fourier Transform, Runge-Kutta algorithms, gamma functions, etc. etc. They are all there and they are all free.

### Outputting data

For the same security reasons discussed above, you cannot simply save calculated data to the user's local drive and you cannot place it onto the Clipboard programatically. You can save it to a server somewhere and the user can then download it, but we all know that's a hassle. Instead, the data are placed in a TextArea (described above) and with a Ctrl-A, Ctrl-C the user has it on the Clipboard. If it's output in tab separated format it pastes straight into Excel. So let's output our input data and the fitted values from the previous example so the user can plot the results in Excel (though, of course, you will have already plotted the fitted curve using a Flot graph!). The TextArea is called OutData. As a bonus, the code shows you how to read out values from array variables which you have created by "pushing" data pairs.

``````var yCalc, outString="", xv,yv
for(i=0;i<NData;i++)
{
xv=DataPairs[i];
yv=DataPairs[i]
//This is inelegant code just to show the principle
yCalc=TheFit.equation+TheFit.equation*x+TheFit.equation*x*x+TheFit.equation*x*x*x
//tab separated then new line at the end
outString+=xv.toFixed(2)+"\t"+yv.toFixed(2)+"\t"+yCalc.toFixed(2)+"\n"
}
\$('#OutData').val(outString)``````