Skip to content

Instantly share code, notes, and snippets.

@emmaly
Created October 21, 2021 03:46
Show Gist options
  • Save emmaly/73064f587bd050a30760817704b29abb to your computer and use it in GitHub Desktop.
Save emmaly/73064f587bd050a30760817704b29abb to your computer and use it in GitHub Desktop.
Google Sheet Style Janitor
const DEBUG = false;
function onEdit(e) {
ScriptProperties.setProperties({
"dirty": "true",
"lastHumanEdit": (new Date()).toJSON(),
});
}
function janitor() {
const props = ScriptProperties.getProperties();
// is it dirty?
const isDirty = props["dirty"];
if (DEBUG) Logger.log("Dirty Floor?");
if (isDirty !== "true") return;
if (DEBUG) Logger.log("Dirty Floor!");
// is it safe to clean now?
const lastHumanEditProp = props["lastHumanEdit"];
if (DEBUG) Logger.log("LHE?");
if (lastHumanEditProp === null) return;
if (DEBUG) Logger.log("LHE!");
const now = new Date();
const lastHumanEdit = new Date(lastHumanEditProp);
const nextDuty = new Date(1000*(lastHumanEdit/1000 + (60 * 2))); // 2 minutes since last edit
if (DEBUG) Logger.log(now);
if (DEBUG) Logger.log(lastHumanEdit);
if (DEBUG) Logger.log(nextDuty);
if (DEBUG) Logger.log("Too soon?");
if (now < nextDuty) return; // too soon?
if (DEBUG) Logger.log("Nope!");
cleanupFormat();
ScriptProperties.setProperties({
"dirty": "false",
"lastCleanup": (new Date()).toJSON(),
});
}
function cleanupFormat() {
const TRANSACTIONS_SHEET_ID = 0;
let sheet = SpreadsheetApp.getActiveSheet();
try {
sheet = SpreadsheetApp
.getActiveSpreadsheet()
.getSheets()
.filter(s => s.getSheetId() === TRANSACTIONS_SHEET_ID)[0];
} catch(e) {Logger.log(e)}
if (sheet.getSheetId() !== TRANSACTIONS_SHEET_ID) return; // only care about Transactions sheet
const CFR = sheet.getConditionalFormatRules();
sheet
.getRange(
sheet.getFrozenRows()+1,
sheet.getFrozenColumns()+1,
sheet.getLastRow()-sheet.getFrozenRows(),
sheet.getLastColumn()-sheet.getFrozenColumns()
)
.clearFormat();
sheet.setConditionalFormatRules(CFR);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment