What are rangelists
var formats = [ { range: sheet.getRange("a2:a7"), format: { backgrounds:"red", fontColors:"white", fontStyles:"normal" } },{ range: sheet.getRange("b2:b7"), format: { backgrounds:"yellow", fontColors:"black", fontStyles:"normal" } },{ range: sheet.getRange("c2:c7"), format: { backgrounds:"red", fontColors:"white", fontStyles:"normal" } },{ range: sheet.getRange("d2:f7"), format: { backgrounds:"darkgray", fontColors:"white", fontStyles:"italic" } }, { range: sheet.getRange("a1:g1"), format: { wraps:true, backgrounds:"yellow", fontWeights:'bold', fontColors:"black" } }];
along with a function like this.
function setFormats (range, format) { // if there's anything to do var atr = range.getNumRows(); var atc = range.getNumColumns(); if(atc && atr){ // for every format mentioned Object.keys(format).forEach (function (f) { // check method exists and apply it var method = 'set'+f.slice(0,1).toUpperCase()+f.slice(1).replace (/s$/,"").replace(/ies$/,"y"); if (typeof range[method] !== "function") throw 'unknown format ' + method; range[method](format[f]); }); } };
executed like this
formats.forEach (function (f) { setFormats (f.range, f.format); });
That gives this
But looking at the execution log, we get these set format calls. Not a huge problem but with lots of columns and formats, this could mount up
Range.setBackground([red]) [0.058 seconds] Range.setFontColor([white]) [0.001 seconds] Range.setFontStyle([normal]) [0 seconds] Range.setBackground([yellow]) [0 seconds] Range.setFontColor([black]) [0 seconds] Range.setFontStyle([normal]) [0 seconds] Range.setBackground([red]) [0 seconds] Range.setFontColor([white]) [0 seconds] Range.setFontStyle([normal]) [0 seconds] Range.setBackground([darkgray]) [0 seconds] Range.setFontColor([white]) [0 seconds] Range.setFontStyle([italic]) [0 seconds] Range.setWrap([true]) [0 seconds] Range.setBackground([yellow]) [0 seconds] Range.setFontWeight([bold]) [0 seconds] Range.setFontColor([black]) [0 seconds]
A better way though would be if all the formats like each other could be set at the same time. Rangelists allow us to work with disconnected ranges. It’s more intuitive to think in terms of which formats apply to a range, rather than to think if terms of ranges apply to a format. Here’s a function that inverts the settings above and applies them to a group of ranges in one go. There’s also a fallback there to the other method for any set format methods are not supported by rangeLists (either now or in the future).
function setFormatsRangeList (formats) { // optimize the formatting by collecting like formats together // and organizing by format rather than by range var formatOrgs = formats.reduce (function (p,c) { var sheet = c.range.getSheet(); var sheetId = sheet.getSheetId(); Object.keys(c.format).forEach (function (f) { // make a unique key for the combination of sheet/format/value var key = f+"_"+c.format[f]+"_"+sheetId; // initialize if we didn't see it before p[key] = p[key] || { value:c.format[f], format:f, ranges:[], sheet:sheet }; // collect the ranges this same format applies to p[key].ranges.push (c.range); }); return p; },{}); // now we can apply formats using rangelists Object.keys (formatOrgs).forEach (function (d) { var o = formatOrgs[d]; // make a rangelist of each range to which this applies var rangeList = o.sheet.getRangeList (o.ranges.map(function (e) { return e.getA1Notation(); })); // get rid of plural (this makes format object compatible between both methods) var method = "set"+o.format.slice(0,1).toUpperCase()+o.format.slice(1).replace (/s$/,"").replace(/ies$/,"y"); // ideally we'll use a range list if (typeof rangeList[method] === 'function') { rangeList[method](o.value); } // so there wasnt a rangelist version - lets try the other way else if (typeof o.ranges[0][method] === 'function') { // reconstruct a format object var t = {}; t[o.format] = o.value; o.ranges.forEach (function (r) { setFormats (r , t) }); } else { throw 'unknown format/method ' + o.format + '/' + method +'/'+ methods;; } }); // return what we made return formatOrgs; }
executed like this, using the same formats definition as before
setFormatsRangeList( formats );
The inverted format it generates looks like this
//The inverted format it applies looks like this [{ "value": "red", "format": "backgrounds", "ranges": ["A2:A7", "C2:C7"], "sheet": "test" }, { "value": "white", "format": "fontColors", "ranges": ["A2:A7", "C2:C7", "D2:F7"], "sheet": "test" }, { "value": "normal", "format": "fontStyles", "ranges": ["A2:A7", "B2:B7", "C2:C7"], "sheet": "test" }, { "value": "yellow", "format": "backgrounds", "ranges": ["B2:B7", "A1:H1"], "sheet": "test" }, { "value": "black", "format": "fontColors", "ranges": ["B2:B7", "A1:H1"], "sheet": "test" }, { "value": "darkgray", "format": "backgrounds", "ranges": ["D2:F7"], "sheet": "test" }, { "value": "italic", "format": "fontStyles", "ranges": ["D2:F7"], "sheet": "test" }, { "value": true, "format": "wraps", "ranges": ["A1:H1"], "sheet": "test" }, { "value": "bold", "format": "fontWeights", "ranges": ["A1:H1"], "sheet": "test" }]
And the execution log (about half the number of set formats as previously)
RangeList.setBackground([red]) [0.064 seconds] RangeList.setFontColor([white]) [0 seconds] RangeList.setFontStyle([normal]) [0 seconds] RangeList.setBackground([yellow]) [0 seconds] RangeList.setFontColor([black]) [0 seconds] RangeList.setBackground([darkgray]) [0 seconds] [RangeList.setFontStyle([italic]) [0 seconds] RangeList.setWrap([true]) [0 seconds] RangeList.setFontWeight([bold]) [0 seconds]
{ range: sheet.getRange("g2:g7"), format: { background:"orange", fontWeights:'normal', fontColors:"white", values:new Date().getTime() } }
And here’s what happens
1EbLSESpiGkI3PYmJqWh3-rmLkYKAtCNPi1L2YCtMgo2Ut8xMThfJ41Ex
There’s more fiddler stuff here
- A functional approach to fiddling with sheet data
- Unique values with data fiddler
- More sheet data fiddling
- Fiddling with text fields that look like dates
- A functional approach to updating master sheet
- Populating sheets with API data using a Fiddler
- Header formatting with fiddler
- Formatting sheet column data with fiddler
- Styling Gmail html tables
- Sorting Google Sheet DisplayValues
- A functional approach to fiddling with sheet data
- A functional approach to updating master sheet
- A recursive extend function for Apps Script
- A webapp to share copies of the contents of folders
- Abstracting services with closures
- Add-on spinner
- Addressing namespace and library methods from google.script.run
- Anonymous user registration with the Apps Script PropertiesService
- Apps for Office – binding example comparison
- Apps Script as a proxy
- Apps Script const scoping problems
- Calculating image dimensions in server side apps script
- Calculating the last day of a given weekday in the month
- Canvasser
- Chaining JavaScript
- Changing class properties dynamically
- Checking the argument types in Apps Script
- Cleaning up a document format
- Cleaning up heading levels
- Column numbers to characters
- Composing functions and functional programming
- Configurable canvas meter
- Convert JSON to XML
- Converting SVG to PNG with JavaScript
- Converting timestamps to dates formula
- Copying canvas and svg images from your Add-on
- Copying to new host location
- Copying to new host location
- Counting script and library usage
- Create sha1 signatures with apps script
- Creating a key digest to use for a cache key or to compare content
- Creating a pile of files list from Google Drive
- Creating and working with transposed sheet data arrays
- Cross Origin Resource sharing (CORS)
- CryptoJS libraries for Google Apps Script
- Custom checking for exponential backoff
- Data wrangling with named columns in Google Spreadsheet
- Dealing with objects that are too large for the property or cache store
- Detecting Spreadsheet tables automatically with Google Apps Script
- Direction minimizer – other usages
- Do something useful with GAS in 5 minutes
- Dynamically creating tables with clusterize.js
- EasyCron Library
- ES6 JavaScript features
- Exponential backoff
- Exponential backoff for promises
- Fiddler and rangeLists
- Fiddling with text fields that look like dates
- Filling ranges in Google Sheets
- Finding a Drive App folder by path
- Finding where Drive hosting is being used in Sites
- Flattening an object with dot syntax
- Flattening and unflattening objects to spreadsheets
- Formatting GraphQL queries
- Formatting sheet column data with fiddler
- From notes to frequencies and back again
- From Xml to JSON
- Generating and managing random lists with JavaScript and Apps Script
- Generating coupon codes with expiry dates
- Generating test data for sheets and tables
- Get GAS library info
- Getting an htmlservice template from a library
- Getting insights into Sheets performance
- Google Drive as cache
- Header formatting with fiddler
- Highlight duplicate rows in a sheet – map and reduce
- Highlight duplicate rows in a sheet – map, filter and every
- How to determine what kind of object something is in Apps Script
- How to get stats about youtube videos in your channel with apps script
- How to pass non stringifyable objects to html service
- How to transpose spreadsheet data with apps script
- Identify duplicates on Drive
- Identifying hosted files
- Implementing a client side progress bar reporting on server side work for htmlService
- Importing Predictwise data
- Improved namespace pattern for Apps Script
- Including the stack in custom errors
- JavaScript closures – how, where and why
- JavaScript currying and functional programming
- JavaScript currying and functional programming – even more
- JavaScript recursion primer
- JSONP and JSON and Google Apps Script webapps
- Loading large JSON datasets into BigQuery with Apps Script
- Logging differences in strings in Apps Script
- Measuring library load speed
- Migrating user and script properties
- Minimizing maps directionfinder api calls
- More client server code sharing
- More recursion – parents and children
- More sheet data fiddling
- Multiple inserts in Fusion Tables
- Namespaces in libraries and scripts
- Normalizing the header level of blank paragraphs
- Optimizing showing and hiding rows and columns
- Organizing asynchronous calls to google.script.run
- Organizing parallel streams of server calls with google.script.run promises
- Parallel process orchestration with HtmlService
- Passing data to html service
- Patching site html
- Populating sheets with API data using a Fiddler
- Proxy jsonp
- Pseudo binding in HTML service
- Queuing asynchronous tasks with rate limit and concurrency constraints
- Recursive async functions
- Removing duplicate paragraphs
- Reporting file, function and line number in Apps Script
- Resumable uploads – writing large files to Drive with Apps Script
- Reusing html stuff between Apps Script projects
- Roughly matching text
- Serving apps script to JavaScript app
- Sharing code between client and server
- Shortcut for adding nested properties to a JavaScript object
- Simple server side polling
- Sorting Google Sheet DisplayValues
- Squeezing more into (and getting more out of) Cache services
- Styling Gmail html tables
- Summarizing emails to a sheet
- SunCalc
- TimeSimmer : An adjustable timer for apps that need to speed up or slow down time
- Transform dates for add-on transfer
- Transposing sheet data
- Traversing a tree
- Unique values with data fiddler
- Unnesting data to sheet values
- Untangling with promises
- Use Drive properties to find app files
- Use promise instead of callback for settimeout
- Using Advanced Drive service to convert files
- Using Apps Script for xml json conversion
- Using array formulas to improve performance
- Using crossfilter with Google Apps Script
- Using D3 in server side Gas
- Using es6 promises server side in Apps Script
- Using Es6 with Apps Script
- Using exponential backoff with github api – dealing with data “in preparation”
- Using Google sheets via Bigquery from Apps Script
- Using named locks with Google Apps Scripts
- Using promises to orchestrate Html service polling
- Using promises with apps script
- Using the Itunes API with Apps Script
- Using the slideshare API from Apps Script
- Using timing functions to get insight into Sheets
- Watching docs for changes
- Watching for server side changes from the client html service
- What JavaScript engine is Apps Script running on?
- Why Base64
- Zipping to make stuff fit in cache or properties service.