Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Forum {
- constructor() {
- this._users = [];
- this._questions = [];
- this.id = 1;
- this.loggedUsers = [];
- }
- register(username, password, repeatPassword, email) {
- const usernameCheck = this._users.find((o) => { return o.email === email || o.username === username });
- if (!username || !password || !repeatPassword || !email) {
- throw Error("Input can not be empty");
- }
- if (password !== repeatPassword) {
- throw Error("Passwords do not match");
- }
- if (usernameCheck) {
- throw Error('This user already exists!');
- }
- this._users.push({ username, password, email });
- return `${username} with ${email} was registered successfully!`
- }
- login(username, password) {
- const usernameCheck = this._users.find((o) => { return o.password === password || o.username === username });
- if (!usernameCheck) {
- throw Error("There is no such user");
- } else {
- this.loggedUsers.push(username);
- return "Hello! You have logged in successfully";
- }
- }
- logout(username, password) {
- const usernameCheck = this._users.find((o) => { return o.password === password || o.username === username });
- if (!usernameCheck) {
- throw Error("There is no such user");
- } else {
- let index = this.loggedUsers.indexOf(username);
- this.loggedUsers.splice(index, 1);
- return "You have logged out successfully";
- }
- }
- postQuestion(username, question) {
- const usernameCheck = this._users.find((o) => { return o.username === username });
- if (!this.loggedUsers.includes(username) || !usernameCheck) {
- throw Error("You should be logged in to post questions");
- }
- if (!question) {
- throw Error("Invalid question");
- }
- this._questions.push({ username, question, id: this.id, answer: [] });
- this.id++;
- }
- postAnswer(username, questionId, answer) {
- const usernameCheck = this._users.find((o) => { return o.username === username });
- const idCheck = this._questions.find((o) => { return o.id === questionId });
- if (!this.loggedUsers.includes(username) || !usernameCheck) {
- throw Error("You should be logged in to post answers");
- }
- if (!answer) {
- throw Error("Invalid answer");
- }
- if (!idCheck) {
- throw Error("There is no such question");
- }
- idCheck.answer.push([username, answer]);
- return "Your answer has been posted successfully";
- }
- showQuestions() {
- let result = [];
- for (const line of this._questions) {
- result.push(`Question ${line.id} by ${line.username}: ${line.question}`)
- for (const x of line.answer) {
- result.push(`---${x.shift()}: ${x.shift()}`);
- }
- }
- return result.join('\n');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement