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