Last active
April 15, 2024 14:57
-
-
Save ku6ryo/c9a6f520705e035895324effd00e5fc1 to your computer and use it in GitHub Desktop.
Lottery script for Google App Script
This file contains hidden or 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
| /** | |
| * Lottery. Returns a won prize ID | |
| * Expected sheet structure. Please do not add header in the sheet. | |
| * | ID of prize | name of prize | num of stock | | |
| * | |
| * Example (https://docs.google.com/spreadsheets/d/1Z_G_VducsGqGtpLtzfEEaTE-7RSydmBgbOrGRUyt8uE/edit?usp=sharing) | |
| * | 1 | T shirt | 10 | | |
| * | 2 | Notepad | 5 | | |
| * | 4 | Sticker | 30 | | |
| */ | |
| function lottery() { | |
| const ss = SpreadsheetApp.getActiveSpreadsheet(); | |
| const sheet = ss.getSheetByName("prizes"); | |
| const range = sheet.getRange('A1:C100'); | |
| const rows = range.getValues().map((row, i) => [i, String(row[0]), Number(row[2])]).filter(row => !!row[1] && row[2] > 0) | |
| const totalStock = rows.reduce((r, row) => r + row[2], 0) | |
| if (totalStock == 0) { | |
| return null | |
| } | |
| const stockIndex = Math.floor(Math.random() * totalStock) | |
| let currentStock = 0 | |
| for (let i = 0; i < rows.length; i++) { | |
| const row = rows[i] | |
| const stock = row[2] | |
| if (stockIndex <= currentStock + stock) { | |
| const prizeIndex = row[0] | |
| const cell = sheet.getRange(prizeIndex + 1, 3); | |
| cell.setValue(stock - 1); | |
| return row[1]; | |
| } | |
| currentStock += stock; | |
| } | |
| throw new Error("Unexpected error") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment