Last active
November 2, 2018 23:40
-
-
Save jmas/432f386d0c9caab7163f70bf875bfcb1 to your computer and use it in GitHub Desktop.
Google script sheet API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createSheetApi(sheetName) { | |
var doc = SpreadsheetApp.getActiveSpreadsheet(); | |
var sheet = doc.getSheetByName(sheetName); | |
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; | |
function mapValues(values) { | |
var data = {}; | |
for (var i=0, length=headers.length; i<length; i++) { | |
data[headers[i]] = values[i]; | |
} | |
return data; | |
} | |
const methods = { | |
find: function(compare) { | |
var values = sheet.getDataRange().getValues(); | |
for (var index=0, length=values.length; index<length; index++) { | |
if (compare(mapValues(values[index]))) { | |
return index; | |
} | |
} | |
return null; | |
}, | |
get: function(index) { | |
var values = sheet.getRange(index, 1, 1, sheet.getLastColumn()).getValues()[0]; | |
return mapValues(values); | |
}, | |
remove: function(index) { | |
sheet.deleteRow(index); | |
}, | |
insert: function(data) { | |
var index = sheet.getLastRow()+1; | |
methods.update(index, data); | |
return index; | |
}, | |
update: function(index, data) { | |
var values = sheet.getRange(index, 1, 1, sheet.getLastColumn()).getValues()[0]; | |
var row = []; | |
for (var i=0, length=headers.length; i<length; i++) { | |
if (headers[i].length > 0) { | |
row.push(data[headers[i]] || values[i]); | |
} | |
} | |
sheet.getRange(index, 1, 1, row.length).setValues([row]); | |
} | |
}; | |
return methods; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment