Skip to content

Instantly share code, notes, and snippets.

@MatthewRiggott
Last active October 31, 2018 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewRiggott/d32b7b974f4385791c5817aad6a09bd9 to your computer and use it in GitHub Desktop.
Save MatthewRiggott/d32b7b974f4385791c5817aad6a09bd9 to your computer and use it in GitHub Desktop.
Google Sheets
// glued a couple stack overflows together
function CELLFORMULA(ref) {
var sheet = SpreadsheetApp.getActiveSheet();
var formula = SpreadsheetApp.getActiveRange().getFormula();
var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
try {
if (args.length == 1) {
var range = sheet.getRange(args[0]);
}
else {
sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
range = sheet.getRange(args[1]);
}
}
catch(e) {
throw new Error(args.join('!') + ' is not a valid range');
}
return range.getFormula();
}
// params is expected to be multiple 1 width x any height ranges
// needs adjustment to accept ranges with more than 1 col width
function permutate(params) {
var result = [];
var counter = [];
var limit = [];
var totalOptions = 1;
for(var i = 0; i < arguments.length; i++) {
var list = arguments[i];
var isArr = Array.isArray(list);
var listSize = isArr ? list.length : 1;
totalOptions = totalOptions * listSize;
counter.push(0);
limit.push(listSize);
}
// brute force by count of all possibilities
for(var a = 0; a < totalOptions; a++) {
var temp = [];
for(var i = 0; i < arguments.length; i++) {
if(limit[i] != 1) {
temp.push(arguments[i][counter[i]][0]); // this translates the permutation index to an actual value
} else {
temp.push(arguments[i]); // if args[i] is a single cell, then its value is simply args[i]
}
}
result.push(temp);
counter[0]++;
for(var i = 0; i < arguments.length; i++) {
// if any index exceeds its limit, set to 0 and increment next index by 1
// repeat for all indexes, this gets the 'next' permutation
if(counter[i] >= limit[i]) {
counter[i] = 0;
counter[i+1]++;
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment