Spreadsheet To Google Form

public
ramabena.rb Oct 30, 2024 Never 55
Clone
JavaScript SpreadsheetToGoogleForm 73 lines (62 loc) | 2.68 KB
1
/**
2
* Author: Rama Bena
3
* Year: 2024
4
* Description: This script creates a Google Form with multiple-choice questions based on data from a Google Sheet.
5
* The form is moved to the same folder as the spreadsheet.
6
*
7
* How to use:
8
* - Ganti beberapa nilai di bawah sesuai kebutuhan
9
* - Pastikan soal pertama ada di baris 2 Kolom B
10
* - Pastikan jawaban benar ada di Kolom C
11
* - Pastikan saat run menggunakan function createQuizForm
12
*/
13
14
function createQuizForm() {
15
const FORM_NAME = "Bahasa Inggris"; // Judul google form yang diinginkan
16
const SHEET_NAME = "soal"; // Nama sheet (bagian bawah spreadsheet)
17
const NUMBER_QUESTIONS = 50; // Banyak soal
18
const NUMBER_CHOICES = 4; // Banyak pilihan jawaban
19
const POINTS_PER_QUESTION = 2; // Poin per soal
20
const IS_REQUIRED = true; // Semua soal wajib dijawab: true untuk iya, false untuk tidak
21
22
const ss = SpreadsheetApp.getActive();
23
const sheet = ss.getSheetByName(SHEET_NAME);
24
const folder = DriveApp.getFileById(ss.getId()).getParents().next(); // Get the folder containing the spreadsheet
25
26
const questions = sheet.getRange(2, 2, NUMBER_QUESTIONS, 1).getValues();
27
const correctAnswers = sheet.getRange(2, 3, NUMBER_QUESTIONS, 1).getValues();
28
const choices = sheet.getRange(2, 3, NUMBER_QUESTIONS, NUMBER_CHOICES).getValues();
29
const randomizedChoices = choices.map(shuffleArray);
30
31
Logger.log("Banyak Soal : " + NUMBER_QUESTIONS);
32
33
const form = FormApp.create(FORM_NAME);
34
form.setIsQuiz(true);
35
36
for (let i = 0; i < NUMBER_QUESTIONS; i++) {
37
Logger.log('Soal ke : ' + (i + 1));
38
const question = questions[i][0];
39
const correctAnswer = correctAnswers[i][0];
40
41
Logger.log('Question: ' + question);
42
Logger.log('Correct Answer: ' + correctAnswer);
43
Logger.log('Choices: ' + randomizedChoices[i]);
44
45
const item = form.addMultipleChoiceItem();
46
const formChoices = randomizedChoices[i].map(choice => item.createChoice(choice, choice === correctAnswer));
47
48
item.setTitle(question)
49
.setPoints(POINTS_PER_QUESTION)
50
.setChoices(formChoices)
51
.setRequired(IS_REQUIRED);
52
}
53
54
// Move the form to the same folder as the spreadsheet
55
const formFile = DriveApp.getFileById(form.getId());
56
folder.addFile(formFile);
57
DriveApp.getRootFolder().removeFile(formFile); // Remove from root folder
58
}
59
60
/**
61
* Randomly shuffles an array
62
* @param {Array} array - The array to shuffle
63
* @return {Array} The shuffled array
64
*/
65
function shuffleArray(array) {
66
for (let i = array.length - 1; i > 0; i--) {
67
const j = Math.floor(Math.random() * (i + 1));
68
const temp = array[i];
69
array[i] = array[j];
70
array[j] = temp;
71
}
72
return array;
73
}