Javascript consolidating if statements - javascript

I was told I should consolidate my if statements. I'm not sure how to do this? Also, is there anything else wrong in this script? It is for a google doc script.
function onEdit(e) {
var colorA = "yellow";
var colorB = "#dddddd";
var colorC = "#dddddd";
var sheet = e.source.getActiveSheet();
var range = e.source.getActiveRange();
// 3 is column C
if (range.getColumn() == 3) {
if (range.getValue() != "") {
sheet.insertRowAfter(range.getRow());
var r = range.getRow() + 1;
sheet.getRange("A" + r + ":H" + r).setBackgroundColor(colorC);
}
}
if (e.source.getActiveRange().getColumn() == 3 ||
e.source.getActiveRange().getColumn() == 8) {
var rows = sheet.getMaxRows();
//two ranges
//column C
var rangeC = sheet.getRange("C1:C"+rows);
var valuesC = rangeC.getValues();
//column H range
var rangeH = sheet.getRange("H1:H"+rows);
var colorH = rangeH.getBackgroundColors();
var valuesH = rangeH.getValues();
//iterate over each row in column C and H
//then change color
for (var row = 0; row < valuesC.length; row++) {
//check for columnC and column H
if (valuesC[row][0] != "" && valuesH[row][0] == "") {
colorH[row][0] = colorA;
} else if (valuesH[row][0] != "") {
colorH[row][0] = colorB;
}
}
sheet.getRange("H1:H" + rows).setBackgroundColors(colorH);
}
}
​
Here is the other one
ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "New PO", functionName: "NewPO"}];
ss.addMenu("New PO", menuEntries);
}
function NewPO() {
SpreadsheetApp.getActiveSheet().insertRowsBefore(1,6);
// Adjust this range accordingly, these are the cells that will be
// copied. Format is getRange(startRow, startCol, numRows, numCols)
ss.getSheetByName("PO Form").getRange(1, 1, 6, 8)
.copyTo(SpreadsheetApp.getActiveSheet().getRange(1, 1, 6, 8));
}
function onEdit(e) {
var ss = e.source.getActiveSheet();
var r = e.source.getActiveRange();
// 1 is A, 2 is B, ... 8 is H
if (r.getColumn() == 8 && r.getValue() == "x") {
r.setValue(Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"));
}
}
​

Besides what murray noted, there are several instances where you repeat the same expression:
if (e.source.getActiveRange().getColumn() == 3 ||
e.source.getActiveRange().getColumn() == 8) {
could be:
var col = e.source.getActiveRange().getColumn();
if(col == 3 || col == 8) {
This applies to a lesser extent to:
if (valuesC[row][0] != "" && valuesH[row][0] == "") {
colorH[row][0] = colorA;
} else if (valuesH[row][0] != "") {
colorH[row][0] = colorB;
}
which could be (for instance):
var hRow = colorH[row];
if (valuesC[row][0] != "" && valuesH[row][0] == "") {
hRow[0] = colorA;
} else if (valuesH[row][0] != "") {
hRow[0] = colorB;
}

only thing i can see:
// 3 is column C
if (range.getColumn() == 3) {
if (range.getValue() != "") {
// 3 is column C
if (range.getColumn() == 3 && range.getValue() != "") {

Related

OnEdit function with google Spreadsheet

I am still a newbie in this, but I want to run Onedit function script on google spreadsheet in a way that I will only get value on column E if the value on column D is "completed" and at the same time I will get value on column F depending on the value on B1 ( and that's only if the column D is"completed"). here is my spreadsheet: https://docs.google.com/spreadsheets/d/1-xLH3mb0fGngocOleCNExEmP6FnDMEFg2uLFXC10XEk/edit#gid=0
function onEdit(e){
var s = SpreadsheetApp.getActiveSpreadsheet();
if( s.getName() == "Hub" ){
var r = s.getActiveCell();
if (r.getColumn() == 4) {
var timecell = r.offSet(0, 1);
var assldapv = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Hub").getRange("B1").getValue();
var assldapo = r.offset(0, 2);
if ( r.getValue() === 'completed' ) {
timecell.setValue(new Date());
assldapo.setValue(assldapv); }
However this function is not working, so can you please give me a template on how to proceed with such script.
Try this
function onEdit(e) {
var sh = e.range.getSheet();
if (sh.getName() == "Hub" && e.range.columnStart == 4 && e.value == "completed") {
var timecell = e.range.offSet(0, 1);
var assldapv = sh.getRange("B1").getValue();
var assldapo = e.range.offset(0, 2);
timecell.setValue(new Date());
assldapo.setValue(assldapv);
}
}

tic tac toe how to keep the game on until win or tie

I am writing a tic tac toe game using JavaScript(no DOM) in console.
I started by doing only one player game and only with 'X'. When the player chooses the row index and the column index and then it store inside an array(Move), but I'm stuck, the player able to do only one move, and that's it. I really dont know what to do from there.
// Variables
let playerName, playerMove = [],
playerShape, boardGame;
// Functions
// Get And Check Name
function getCheckName() {
let name = prompt("Please Enter Your Name");
while (name == null || !isNaN(name) || name == ' ') {
alert("Numbers And Spaces Not Allowed");
name = prompt("Please Enter Your Name");
}
alert("Welcome " + name);
return name;
}
playerName = getCheckName();
playerShape = 'X';
//----------------------------------------------------------------------------------------
// // Get Row And Col
function getRowAndCol() {
let row, col, rowAndColArr = [];
row = parseInt(prompt("Please Enter A Row"));
while (row > 2 || row < 0 || row === null || isNaN(row)) {
alert("Not a Valid Row number");
row = parseInt(prompt("Please Enter A Row"));
}
rowAndColArr[rowAndColArr.length] = row;
col = parseInt(prompt("Please Enter A Col"));
while (col > 2 || col < 0 || col === null || isNaN(col)) {
alert("Not a Valid Col number");
col = parseInt(prompt("Please Enter A Col"));
}
rowAndColArr[rowAndColArr.length] = col;
return rowAndColArr;
}
playerMove = getRowAndCol();
//----------------------------------------------------------------------------------------
// Board Game
boardGame = [
["_", "_", "_"],
["_", "_", "_"],
["_", "_", "_"]
];
function boardFn(board, move) {
for (let rw = 0; rw < board.length; rw++) {
for (let cl = 0; cl < board[rw].length; cl++) {
while (rw === move[0] && cl === move[1] && board[rw][cl] === "_") {
board[rw][cl] = playerShape;
}
}
}
return board;
}
let keepGame = boardFn(boardGame, playerMove);
do {
} while (condition);
console.log(checkWinner());
//----------------------------------------------------------------------------------------
// Check Win
function equal3(a, b, c) {
return (a == b && b == c && a != "_");
};
function checkWinner() {
let winner = null;
// Win In Horizontal
for (let rw = 0; rw < 3; rw++) {
if (equal3(boardGame[rw][0], boardGame[rw][1], boardGame[rw][2])) {
winner = boardGame[rw][0];
alert(playerName + " You Won line");
}
}
// Win In Vertical
for (let cl = 0; cl < 3; cl++) {
if (equal3(boardGame[0][cl], boardGame[1][cl], boardGame[2][cl])) {
winner = boardGame[cl][0];
alert(playerName + " You Won col");
}
}
// Win In Diagonal
if (equal3(boardGame[0][0], boardGame[1][1], boardGame[2][2])) {
winner = boardGame[0][0];
alert(playerName + " You Won diagonal");
}
// Win In Diagonal (Other Way)
if (equal3(boardGame[2][0], boardGame[1][1], boardGame[0][2])) {
winner = boardGame[2][0];
alert(playerName + " You Won digonal other");
}
return winner;
}
Updated code for two players
var board = [
["_", "_", "_"],
["_", "_", "_"],
["_", "_", "_"]
];
//This function will prompt and get user name
function getName(player) {
let name = prompt("Please Enter " + player + " Name");
while (name == null || !isNaN(name) || name == ' ') {
alert("Numbers And Spaces Not Allowed");
name = prompt("Please Enter " + player + " Name");
}
alert("Welcome, " + name + "!");
return name;
}
//This function will prompt and get row and column from player
function getRowAndCol(player) {
let row, col, rowAndColArr = [];
row = parseInt(prompt(player + "! Please Enter A Row"));
while (row > 2 || row < 0 || row === null || isNaN(row)) {
alert("Not a Valid Row number");
row = parseInt(prompt(player + "! Please Enter A Row"));
}
rowAndColArr[rowAndColArr.length] = row;
col = parseInt(prompt(player + "! Please Enter A Col"));
while (col > 2 || col < 0 || col === null || isNaN(col)) {
alert("Not a Valid Col number");
col = parseInt(prompt(player + "! Please Enter A Col"));
}
rowAndColArr[rowAndColArr.length] = col;
//This block will check if the given box already marked. If so it will prompt for the move.
if (board[rowAndColArr[0]][rowAndColArr[1]] !== "_") {
alert("Already marked on the given box. Please Enter different row and column.!");
return getRowAndCol(player)
}
return rowAndColArr;
}
//This function will update the position with the given shape according to the move
function boardFn(board, move, shape) {
for (let rw = 0; rw < board.length; rw++) {
for (let cl = 0; cl < board[rw].length; cl++) {
while (rw === move[0] && cl === move[1] && board[rw][cl] === "_") {
board[rw][cl] = shape;
}
}
}
}
//This function will check if it is tie
function isTie() {
for (let rw = 0; rw < board.length; rw++) {
for (let cl = 0; cl < board[rw].length; cl++) {
if( board[rw][cl] === "_" ) {
return false;
}
}
}
return true;
}
//These functions will check whether the current player win or not
function equal3(a, b, c) {
return (a == b && b == c && a != "_");
};
function checkWinner(player) {
let winner = null;
// Win In Horizontal
for (let rw = 0; rw < 3; rw++) {
if (equal3(board[rw][0], board[rw][1], board[rw][2])) {
winner = board[rw][0];
alert(player + " You Won line");
}
}
// Win In Vertical
for (let cl = 0; cl < 3; cl++) {
if (equal3(board[0][cl], board[1][cl], board[2][cl])) {
winner = board[cl][0];
alert(player + " You Won col");
}
}
// Win In Diagonal
if (equal3(board[0][0], board[1][1], board[2][2])) {
winner = board[0][0];
alert(player + " You Won diagonal");
}
// Win In Diagonal (Other Way)
if (equal3(board[2][0], board[1][1], board[0][2])) {
winner = board[2][0];
alert(player + " You Won digonal other");
}
return winner;
}
var player1 = getName("Player 1") // getting player 1 name
alert(player1 + "! Your shape is 'X'");
var player2 = getName("Player 2") // getting player 2 name
alert(player2 + "! Your shape is 'O'");
// Variables to maintain current players and shape
var currentPlayer = ""
var currentShape = ""
// This block will get and validate moves until we get a winner
while (true) {
// This block will switch player after a move
if (currentPlayer == "") {
currentPlayer = player1;
currentShape = "X";
} else if (currentPlayer == player1) {
currentPlayer = player2;
currentShape = "O";
} else {
currentPlayer = player1;
currentShape = "X";
}
var move = getRowAndCol(currentPlayer);
boardFn(board, move, currentShape);
var status = "";
for (var i in board) {
for (var j in board[i]) {
status += board[i][j] + " ";
}
status += "\n";
}
console.log(status);
console.log("-------------------------------");
if (checkWinner(currentPlayer)) {
break;
} else if (isTie()) {
alert("Game tied.!")
break;
}
}

How to remove nth-1 array index in Javascript while doing Excel export

How do I remove Nth-1 rows from an array?
I am trying to export my records in Excel but am getting some html code in my Excel file. The reason for this is I am trying to remove that row but am not able to delete that particular row, because that row is dynamically changing.
I am getting data in an array while checking it in debug mode.
Can anyone help me with how I can remove total length of Array-1? For example, if I have 40 records then I want remove 39th position.
This is my JS Code:
[![$(function () {
var exportFlag = false;
var reportGrid = $(time.report.gridId);
if (reportGrid.length > 0) {
$(time.report.gridId).data("kendoGrid").bind("excelExport",
function(e) {
if (!exportFlag) {
var sheet = e.workbook.sheets\[0\];
var columns = e.sender.columns;
e.preventDefault();
exportFlag = true;
setTimeout(function() {
e.sender.saveAsExcel();
},
1000);
} else {
// e.sender.hideColumn(0);
//e.sender.hideColumn(e.sender.columns.length + 1);
exportFlag = false;
}
});
});][1]][1]
onExcelExport: function (e) {
setTimeout("location.reload(true);", 1000);
e.sender.hideColumn("OutIp");
e.sender.hideColumn("InIp");
var sheet = e.workbook.sheets[0];
var rows = sheet.rows;
var rowIdx, colIdx, cells, cell;
for (rowIdx = 0; rowIdx < rows.length; rowIdx++) {
if (rows[rowIdx].type === "data") {
cells = rows[rowIdx].cells;
var color = "#ffffff";
if (cells[0].value === true) {
color = "#ff0000";
}
for (colIdx = sheet.freezePane.colSplit; colIdx < cells.length; colIdx++) {
cell = cells[colIdx];
cell.background = color;
//cell.value = kendo.toString(cell.value, "c");
if (colIdx === 4) {
cell.value = cell.value.Hours + ":" + cell.value.Minutes;
}
else if (cell.value !== undefined && cell.value !== null && cell.value.Hours !== undefined) {
cell.value = utcTimeToLocalTime(cell.value.Hours + ":" + cell.value.Minutes);
}
else if (cell.value !== undefined && cell.value !== null && cell.value === true) {
cell.value = "Yes";
}
else if (cell.value !== undefined && cell.value !== null && cell.value === false) {
cell.value = "No";
}
}
}
}
},
To remove the last-but-one element of any array you could do:
var numberElements = yourArray.length;
var targetElement = numbElements - 1;
// second parameter is number of elements to remove
yourArray.splice(targetElement, 1);

OnEdit need to send emails from a column

When in column O cell is mentioned "Shipped" I want to send emails in column C (with corresponding row)
Need support to get this script right
function sendEmail(e) {
var thisSheet = e.source.getActiveSheet();
if (thisSheet.getName() !== 'CRM' || e.range.columnStart !== 15 || e.range.rowStart == 1 || e.value !== 'Shipped') return;
var body, headers = thisSheet.getRange(1, 1, 1, 6)
.getValues()[0],
thisRow = thisSheet.getRange(e.range.rowStart, 1, 1, 6)
.getValues()[0],
recipientsEMail = (thisSheet.getRange.columnStart !==3 || e.range.rowStart ==1)
.getValues()[0],
recipients = recipientsEMail,
subject = "Your Vehicle is shipped " + e.source.getName(),
body = "",
i = 0;
while (i < 6) {
body += headers[i] +' - ' + thisRow[i] +'\n';
i++;
}
MailApp.sendEmail(recipients, subject, body);
}
My sheet
See if this works:
function sendEmail(e) {
var thisSheet = e.source.getActiveSheet();
if (thisSheet.getName() !== 'CRM' || e.range.columnStart !== 15 || e.range.rowStart == 1 || e.value !== 'Shipped') return;
var body, headers = thisSheet.getRange(1, 1, 1, 15)
.getValues()[0],
thisRow = thisSheet.getRange(e.range.rowStart, 1, 1, 15)
.getValues()[0];
var recipients = thisRow[2];
var subject = "Your Vehicle is shipped " + e.source.getName(),
body = "Dear Customer,\n\nYour vehicle has been shipped from Japan";
MailApp.sendEmail(recipients, subject, body);
}
You didn't say how much columns you need to use to construct the body of the email but that can be easily changed if you increase the number in the while loop.

How to combine several pieces of code in one? (JavaScript)

i got a little problem with my code: i got 3 pieces of code, but i can't combine it together.
All three codes put timestamps in different cells when certain cells change.
If I change cell A1, then in cell B1 insert timestamp. If the change in cell A2, then in cell B2 insert timestamp , etc.
Can you help me? Thanks.
1)
function onEdit(event) {
var tsheet = 'Заявки' ;
var lcol = 17;
var rcol = 17;
var tcol = 18;
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
}
}
}
2)
function onEdit(event) {
var tsheet = 'Заявки' ;
var lcol = 15;
var rcol = 15;
var tcol = 16;
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
}
}
}
3)
function onEdit(event) {
var tsheet = 'Заявки' ;
var lcol = 9;
var rcol = 9;
var tcol = 8;
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
}
}
}
Put the column specification in an array:
function onEdit(event) {
var tsheet = 'Заявки' ;
var colspec=[[17,17,18],[15,15,16],[9,9,8]];
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
var i=colspec.length;
while (i>0) {
i--;
if (scol >= colspec[i][0] && scol <= colspec[i][1]) {
s.getRange(r.getRow(), colspec[i][2]).setValue(new Date());
}
}
}
}

Categories