calculator a- add symbol from array on each digit - arrays

var switchBox = "num_txt1";
var signSwitcher = "";
var minNum = Math.max(900000)
var maxNum = Math.max(999999)
num_txt1.border = false;
num_txt2.border = false;
num_txt1.restrict = "0-9";
num_txt2.restrict = "0-9";
var fish:Object = new Object;
Array:
var onesArray: Array = [fish1, fish2, fish3, fish4, fish5, fish6, fish7, fish8, fish9];
var tensArray: Array = [fish10, fish20, fish30, fish40, fish50, fish60, fish70, fish80, fish90];
var hundredsArray: Array = [fish100, fish200, fish300, fish400, fish500, fish600, fish700, fish800, fish900];
var thousandsArray: Array = [fish1k, fish2k, fish3k, fish4k, fish5k, fish6k, fish7k, fish8k, fish9k];
var tenthousandsArray: Array = [fish10k, fish20k, fish30k, fish40k, fish50k, fish60k, fish70k, fish80k, fish90k];
var hundredthousandsArray: Array = [fish100k, fish200k, fish300k, fish400k, fish500k, fish600k, fish700k, fish800k, fish900k];
var millionsArray: Array = [fish1m, fish2m, fish3m, fish4m, fish5m, fish6m, fish7m, fish8m, fish9m];
Buttons (e.g. 1 and 2):
num1_btn.addEventListener(MouseEvent.CLICK, btn1Click);
function btn1Click(event) {
if (switchBox == "num_txt1" && num_txt1.text.length < 6) {
var val1 = num_txt1.text;
num_txt1.text = val1 + "1";
fish = onesArray[0];
onesArray[0].x = 306.05;
onesArray[0].y = 56.05;
var sfish: FishOpening = new FishOpening();
sfish.play();
}
else if (num_txt2.text.length < 6) {
var val2 = num_txt2.text;
num_txt2.text = val2 + "1";
}
}
num2_btn.addEventListener(MouseEvent.CLICK, btn2Click);
function btn2Click(event) {
if (switchBox == "num_txt1" && num_txt1.text.length < 6)
{
var val1 = num_txt1.text;
num_txt1.text = val1 + "2";
}
else if (num_txt2.text.length < 6)
{
var val2 = num_txt2.text;
num_txt2.text = val2 + "2";
}
}
Each digit will be displayed the number of fishes as a symbol from an array when one of the numbers is pressed. There are 6 digits, ones to millions from left to right.

Related

How can I use a script to delete all data on a google spreadsheet?

I have a google form that exports all of the answers to a google sheet. I also have a script that exports my google sheets (aka my form answers) and converts it to json. The problem is, If I make another response on google forms, my script converts both responses into a json when I only want the most recent response to converted. What I need is an addition to my script to delete all rows after it exports the data so when I try again it doesn't take the old responses.
// Tweak the makePrettyJSON_ function to customize what kind of JSON to export.
var FORMAT_ONELINE = 'One-line';
var FORMAT_MULTILINE = 'Multi-line';
var FORMAT_PRETTY = 'Pretty';
var LANGUAGE_JS = 'JavaScript';
var LANGUAGE_PYTHON = 'Python';
var STRUCTURE_LIST = 'List';
var STRUCTURE_HASH = 'Hash (keyed by "id" column)';
/* Defaults for this particular spreadsheet, change as desired */
var DEFAULT_FORMAT = FORMAT_PRETTY;
var DEFAULT_LANGUAGE = LANGUAGE_JS;
var DEFAULT_STRUCTURE = STRUCTURE_LIST;
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{name: "Export JSON for this sheet", functionName: "exportSheet"},
{name: "Export JSON for all sheets", functionName: "exportAllSheets"}
];
ss.addMenu("Export JSON", menuEntries);
}
function makeLabel(app, text, id) {
var lb = app.createLabel(text);
if (id) lb.setId(id);
return lb;
}
function makeListBox(app, name, items) {
var listBox = app.createListBox().setId(name).setName(name);
listBox.setVisibleItemCount(1);
var cache = CacheService.getPublicCache();
var selectedValue = cache.get(name);
Logger.log(selectedValue);
for (var i = 0; i < items.length; i++) {
listBox.addItem(items[i]);
if (items[1] == selectedValue) {
listBox.setSelectedIndex(i);
}
}
return listBox;
}
function makeButton(app, parent, name, callback) {
var button = app.createButton(name);
app.add(button);
var handler = app.createServerClickHandler(callback).addCallbackElement(parent);;
button.addClickHandler(handler);
return button;
}
function makeTextBox(app, name) {
var textArea = app.createTextArea().setWidth('100%').setHeight('200px').setId(name).setName(name);
return textArea;
}
function exportAllSheets(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheetsData = {};
for (var i = 0; i < sheets.length; i++) {
var sheet = sheets[i];
var rowsData = getRowsData_(sheet, getExportOptions(e));
var sheetName = sheet.getName();
sheetsData[sheetName] = rowsData;
}
var json = makeJSON_(sheetsData, getExportOptions(e));
displayText_(json);
}
function exportSheet(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rowsData = getRowsData_(sheet, getExportOptions(e));
var json = makeJSON_(rowsData, getExportOptions(e));
displayText_(json);
}
function getExportOptions(e) {
var options = {};
options.language = e && e.parameter.language || DEFAULT_LANGUAGE;
options.format = e && e.parameter.format || DEFAULT_FORMAT;
options.structure = e && e.parameter.structure || DEFAULT_STRUCTURE;
var cache = CacheService.getPublicCache();
cache.put('language', options.language);
cache.put('format', options.format);
cache.put('structure', options.structure);
Logger.log(options);
return options;
}
function makeJSON_(object, options) {
if (options.format == FORMAT_PRETTY) {
var jsonString = JSON.stringify(object, null, 4);
} else if (options.format == FORMAT_MULTILINE) {
var jsonString = Utilities.jsonStringify(object);
jsonString = jsonString.replace(/},/gi, '},\n');
jsonString = prettyJSON.replace(/":\[{"/gi, '":\n[{"');
jsonString = prettyJSON.replace(/}\],/gi, '}],\n');
} else {
var jsonString = Utilities.jsonStringify(object);
}
if (options.language == LANGUAGE_PYTHON) {
// add unicode markers
jsonString = jsonString.replace(/"([a-zA-Z]*)":\s+"/gi, '"$1": u"');
}
return jsonString;
}
function displayText_(text) {
var output = HtmlService.createHtmlOutput("<textarea style='width:100%;' rows='20'>" + text + "</textarea>");
output.setWidth(400)
output.setHeight(300);
SpreadsheetApp.getUi()
.showModalDialog(output, 'Exported JSON');
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData_(sheet, options) {
var headersRange = sheet.getRange(1, 1, sheet.getFrozenRows(), sheet.getMaxColumns());
var headers = headersRange.getValues()[0];
var dataRange = sheet.getRange(sheet.getFrozenRows()+1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
var objects = getObjects_(dataRange.getValues(), normalizeHeaders_(headers));
if (options.structure == STRUCTURE_HASH) {
var objectsById = {};
objects.forEach(function(object) {
objectsById[object.id] = object;
});
return objectsById;
} else {
return objects;
}
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - rowHeadersColumnIndex: specifies the column number where the row names are stored.
// This argument is optional and it defaults to the column immediately left of the range;
// Returns an Array of objects.
function getColumnsData_(sheet, range, rowHeadersColumnIndex) {
rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;
var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();
var headers = normalizeHeaders_(arrayTranspose_(headersTmp)[0]);
return getObjects(arrayTranspose_(range.getValues()), headers);
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects_(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty_(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders_(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader_(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader_(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum_(letter)) {
continue;
}
if (key.length == 0 && isDigit_(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty_(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum_(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit_(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit_(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose_(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
} ```
This isn't my original script and I am not that knowledgeable in this space so any help is appreciated.
Clear contents on all sheets
function clearAll() {
SpreadsheetApp.getActive().getSheets().forEach(sh => sh.clear());
}

Creating a javascript array to localstorage not returning desired result

I'm trying to create an array to localstorage containing some gear box values, witch I then need again to do some more calculations with specific array[?].value.
The problem I'm encountering is that the created entry returns only 2 array entries, although all entries are there but the " is at the beginning and then at the second last entry and then before and after the last entry.
These are the values generated.
spd_Dev = ["202.391,172.876,120.451,102.601,85.173,72.664,61.701,52.706,45.116,38.510,32.326,27.407,22.910,19.536,16.585,14.195,12.228","10.401"]
When I used to use a fixed array I've entered it as:
var spd_Dev = [202.391, 172.876, 120.451, 102.601, 85.173, 72.664, 61.701, 52.706, 45.116, 38.510, 32.326, 27.407, 22.910, 19.536, 16.585, 14.195, 12.228, 10.401];
So my question is how to write this values to localstorage and read again from localstorage so that I can use this values as an array.
This is what I'm trying to work.
var D_RatioId = data.truck.make + data.truck.model + "D_Ratio"
var G_RatioId = data.truck.make + data.truck.model + "G_Ratio"
var fGr = data.truck.forwardGears;
var gr = data.truck.displayedGear;
var Rpm = data.truck.engineRpm * 100;
var spd = data.truck.speed;
var T_Dia = 1008.3;
if (localStorage.getItem(G_RatioID) == undefined) {
localStorage.setItem(G_RatioID, '');
var fG_Rat = [localStorage.getItem(G_RatioID)];
} else {
var fG_Rat = [localStorage.getItem(G_RatioID)];
}
var spd_Dev = localStorage.getItem(Spd_DevId);
spd_Dev = spd_Dev ? spd_Dev.split(', ') : [];
if (localStorage.getItem("i") == undefined) {
localStorage.setItem("i", 1);
var i = localStorage.getItem("i");
} else {
var i = localStorage.getItem("i");
}
if (i <= fGr && spd > 0.5) {
if (i <= fGr + 1) {
if (i == gr) {
if (RPM > 1450) {
var G_Ratio = Math.abs(Rpm / D_Ratio * (Math.PI * T_Dia / 1000) * 60 / spd / 1000, 2).toFixed(2);
var spd_D = Math.abs(RPM / (RPM / G_Ratio / D_Ratio * (Math.PI * T_Dia / 1000) * 60 / 1000) * 0.821932).toFixed(3);
fG_Rat.push(G_Ratio);
spd_Dev.push(spd_D);
i++;
localStorage.setItem("i", i);
var G_RatioValue = fG_Rat;
var Spd_DevValue = spd_Dev;
SetG_Ratio(G_RatioID, G_RatioValue);
SetSpd_Dev(Spd_DevId, Spd_DevValue);
localStorage.setItem("spd_Dev", JSON.stringify(Spd_DevValue));
}
}
}
}
function SetG_Ratio(G_RatioID, G_RatioValue) {
localStorage.setItem(G_RatioID, G_RatioValue);
console.log(G_RatioID, G_RatioValue);
}
function SetSpd_Dev(Spd_DevId, Spd_DevValue) {
localStorage.setItem(Spd_DevId, Spd_DevValue.toString());
console.log(Spd_DevId, Spd_DevValue, Spd_DevValue.length);
}
if (spd >= 0) {
var spd_Dev = [localStorage.getItem(Spd_DevId)];
var spD_D = JSON.parse(spd_Dev);
for (i = 1; i < (fGr + 1); i++) { // Some more code dependant on the above results //
why don't you use LSM.js? it will make everything simpler. you can put the array as an array so that it will return the full array only, you will not need to use split(),
https://github.com/kevinj045/LSM_js
var lsm = new LSM("G_RatioID");
var G_RatioValue ["202.391,172.876,120.451,102.601,85.173,72.664,61.701,52.706,45.116,38.510,32.326,27.407,22.910,19.536,16.585,14.195,12.228","10.401"];
lsm.set("G_RatioID",G_RatioValue);
console.log(lsm.get("G_RatioID")); // it will return the full array

Looping backwards through data values

I am guessing my logic does not work do to the values I am using in the loop. Not quite sure how to proceed. Thank you.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ash = ss.getSheetByname("Master List C");
var laRow = ash.getLastRow();
var laCol = ash.getLastColumn();
var toMove = [];
var dsh = ss.getSheetByname("Non-Members");
var ldRow = dsh.getLastRow();
var ldCol = dsh.getLastColumn();
var range = ash.getRange(9, 1, laRow, laCol);
var aData = range.getValues();
for (row = aData.length; row >= 9; row--) {
if (aData[row][6] == "No") {
var tmp = [aData[row][0], aData[row][1], aData[row][2], aData[row][3], aData[row][4], aData[row][5], aData[row][8]];
toMove.push(tmp);
dsh.getRange(dsh.getLastRow() + 1, 1, toMove.length, 7).setValues(toMove);
ash.deleteRow(row);
}
}

Google Script array value undefined

i wrote a code that should take a value from a cell and than convert it to the string and than into the array. its working fine. I can see the value of arr in Logs as an array with the input of the cell. For example, in the cell are " dog, cat " and tha arr value in Logs is [dog, cat].
But after i create this array, i would like to make a loop on it. And than i become in Logs, that arr is undefined. Can somebody help me please? im working on it for 2 days :(
Here is my code:
function animal (s,z){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange("SM");
var columnNumber = getColumnNumberOfSM(s);
var rowNumber = getRowNumberOfSM(z);
var colAction = columnNumber + 1;
var action = sheet.getRange(rowNumber, colAction, 1, 1).getValues();
var bar = action.toString();
var arr = [{}];
arr = bar.split(", ");
//return arr; // returns an array [dog, cat]
var foo = arr; // underfined
for (var i = 0; i <= foo.length; ++i) {
if (foo[i] == "dog") {
Logger.log(upload());
}
}
}
now i edit my code and its working fine,but only with "dog" but not with "cat"
function animal(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var action = sheet.getRange("C3").getValue();
var bar = action.toString();
var arr = bar.split(", ");
for (var i = 0; i <= arr.length; ++i) {
if (arr[i] == "dog") { // works
Logger.log(upload());
}
if (arr[i] == "cat") { // doesn't work
Logger.log(upload());
}
}
}
You don't need to initiate arr as blank you can directly initialize it as a result to split method , also one point I didn't get is why do you need to assign arr to foo? You can directly iterate through arr.length and perform the required operation.
Here's my working snippet.
var parts = path.split(",");
for (var i = 0; i < parts.length; i++) {
if (parts[i] == 'dog'){
Logger.log(parts[i]);
}
}

Google Apps Scrit add value to array every time a loop executes

I would like to add "RealData" to my array "tempArr", I am trying to use "push" but I have no experience with it so I can not get it to work. Could you help me out?
for (var i=0; i < data.length; i++) {
var testDate = subDaysFromDate(data[i][0],1)
var DateToCheck = Utilities.formatDate(testDate, "GMT", "dd-MM-yyyy");
var DateToCheckBefore = DateToCheck.split("-");
var DateToCheckAfter = new Date(DateToCheckBefore[2], DateToCheckBefore[1]-1, DateToCheckBefore[0]); //dit is de datum van een row
Row++;
var tempArr = new Array();
var d1 = $d1.split("-");
var d2 = $d2.split("-");
var from = new Date(d1[0], d1[1]-1, d1[2]); // -1 because months are from 0 to 11
var to = new Date(d2[0], d2[1]-1, d2[2]);
if(DateToCheckAfter >= from && DateToCheckAfter <= to){
var KlantNr = sheet.getRange("A"+Row).getValue();
var KlantVoornaam = sheet.getRange("B"+Row).getValue();
var KlantAchternaam = sheet.getRange("C"+Row).getValue();
var HTMLData = KlantNr + "-" + KlantVoornaam + "-" + KlantAchternaam;
var RealData = HTMLData.split("-");
tempArr.push(RealData);
}
}
Logger.log(tempArr);
When you PUSH an array into another you're referencing it, to copy use slice:
tempArr.push(RealData.slice(0));
Also, this is a javascript problem.

Resources