Description
This is a quick little script for populating fields with a number of randomly linked records. For example if you want to give out a prize (like this one), or randomize some email recievers – you can efficiently link to a random profile / consumer / person (or anything for that matter).
See the original source for a video demo of the script.
Script Code
/* C O N F I G */
/* names: fill to match own table*/
let tableToPullFrom = 'table';
let viewToPullFrom = 'view';
let tableToWriteTo = 'table';
let viewToWriteTo = 'view';
let fieldToWriteTo = 'field';
/* settings */
let linksPerRecord = 1;
let unique = true;
/* C O D E */
/* creates list with IDs of all records from the table to pull from */
tableToPullFrom = base.getTable(tableToPullFrom);
viewToPullFrom = tableToPullFrom.getView(viewToPullFrom);
let listOfRecordsToPull = [];
let pullResult = await viewToPullFrom.selectRecordsAsync();
for (let record of pullResult.records) {
listOfRecordsToPull.push({id:record.id});
}
if (listOfRecordsToPull.length < linksPerRecord) {
throw "You can't request more links per record than there are in view to pull from";
}
/* choses a random element from the list and pops it if unique is true */
randomElement = listOfRecordsToPull[Math.floor(Math.random() * listOfRecordsToPull.length)]
if (unique == true) {
var index = listOfRecordsToPull.indexOf(randomElement);
if (index !== -1) listOfRecordsToPull.splice(index, 1);
else console.error('ran out of linked records for your request, add more or turn off the unique setting');
}
/* adds {linksPerRecord} number of links per record in table to write to */
tableToWriteTo = base.getTable(tableToWriteTo);
viewToWriteTo = tableToWriteTo.getView(viewToWriteTo);
let writeResult = await viewToWriteTo.selectRecordsAsync();
for (let record of writeResult.records) {
/* made as set to avoid duplicate errors */
let writeInThisRecord = [];
for (let i = 0; i < linksPerRecord; i++) {
/* chose random */
randomElement = listOfRecordsToPull[Math.floor(Math.random() * listOfRecordsToPull.length)];
/* skip and retry if duplicate */
if (writeInThisRecord.indexOf(randomElement) !== -1) {
i--;
continue;
}
/* pop if unique */
if (unique == true) {
var index = listOfRecordsToPull.indexOf(randomElement);
if (index !== -1) listOfRecordsToPull.splice(index, 1);
else console.error('ran out of linked records for your request, add more or turn off the unique setting');
};
writeInThisRecord.push(randomElement);
/* deal with duplicates */
writeInThisRecord = Array.from(writeInThisRecord);
/* update */
await tableToWriteTo.updateRecordAsync(record,{[fieldToWriteTo]: writeInThisRecord});
}
}
markdown.output('script finished')