Skip to content

Instantly share code, notes, and snippets.

@tallcoleman
Created August 27, 2023 12:42
Show Gist options
  • Save tallcoleman/777b4bc2304fb1a2b7996217893584b8 to your computer and use it in GitHub Desktop.
Save tallcoleman/777b4bc2304fb1a2b7996217893584b8 to your computer and use it in GitHub Desktop.
Intersect() function for Google Apps Script
/**
* Returns the intersection of two ranges, or null if there is no overlap.
* @param {range} r1 Range 1
* @param {range} r2 Range 2
*/
function Intersect(r1, r2) {
if (r1.getSheet().getSheetId() !== r2.getSheet().getSheetId()) return null;
const FIRSTROW = Math.max(r1.getRow(), r2.getRow());
const LASTROW = Math.min(r1.getLastRow(), r2.getLastRow());
const FIRSTCOL = Math.max(r1.getColumn(), r2.getColumn());
const LASTCOL = Math.min(r1.getLastColumn(), r2.getLastColumn());
if (FIRSTROW > LASTROW || FIRSTCOL > LASTCOL) return null;
return r1.getSheet().getRange(FIRSTROW, FIRSTCOL, LASTROW - FIRSTROW + 1, LASTCOL - FIRSTCOL + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment