Monday, July 2, 2018
Adding a Column of Numbers
Adding a Column of Numbers
This morning, while working on an invoice, I once again found myself needing to add a column of numbers, so I decided to write a script to do it:
//DESCRIPTION: Add selected column of numbersNotice the use of search to locate the first digit in the string representing the contents of each line (for which I might have chosen a wiser variable name than "text"). I chose to use the prompt style of alert to simplify copying the result to another application or even into an InDesign document. And, I issued an activate to bring InDesign to the front so that should I be running the script from ESTK, the prompt would be brought in front of the ESTK window.
if (app.documents.length > 0 && app.selection.length > 0) {
addSelection(app.selection[0]);
}
function addSelection(sel) {
var myLines = sel.contents.split(" ");
var total = 0;
for (var j = 0; myLines.length > j; j++) {
total = total + getNumber(myLines[j]);
}
app.activate()
prompt("Result", String(total));
function getNumber(text) {
var start = text.search(/d/);
if (start == -1) return 0;
return Number(text.slice(start));
}
}
Now Im looking at the script, I find myself thinking: what if the column was a column within a table? I reckon theres room for a part 2 to this blog entry!