Could there be a more sophisticated and streamlined method for verifying answers?

My app is designed for students and it automatically generates questions (such as distance/time questions), includes animations, and grades student answers. Here is a preview:

https://i.sstatic.net/br8Ly.png

Achieving my goal Although the code works fine overall, I am looking to enhance one specific part to make it more elegant. I'm curious if there's a JavaScript solution to transform a function that asks 'is it this? is it this? is it this? ...' into 'is it one of these, and if so which one is it?'.

No expected or actual results are provided since the functionality works smoothly without errors. However, here's a link to Stack Blitz for demonstration: https://stackblitz.com/edit/angular-qrldtz?devtoolsheight=33&file=src/app/app.component.ts

Example of HTML with Angular syntax: The iteration over questions displayed on the right-hand side of the image above.

<form [formGroup]="formAnswers" (ngSubmit)="answersSubmitted()">
  <div class="question-container" *ngFor="let question of questionBank[0].questions; let i = index">
      <div class="question-question">{{ question.question }}</div>
      <div class="question-input">
          <input type="text" formControlName="{{ question.id }}" class="answer-input" maxlength="8">
      </div>
  </div>
  <button type="submit" style="float: right;">Submit Answers</button>
</form>

Here's a simplified example of the relevant TypeScript code. The part I aim to streamline is within the 'answersSubmitted()' function which validates student answers against stored values.

formAnswers: FormGroup;
velocity: number = 0;
valueInitialSpeed = {'x': 0, 'y': 0};

// This represents the database of questions. It contains only one sample question for illustration.
questionBank = [
    {
        'questionText': `A tennis ball is hit from an overhand serve towards a net.`, 
        'startVelocityRange': 25.2,
        'angleAppliedRange': 12,
        'xAccelerationRange': 0,
        'yAccelerationRange': 0,
        'gravity': 9.81,
        'startHeightRange': [0, 0],
        'dataGiven': { 'velocity': true, 'yInitSpeed': false, 'xInitSpeed': false},
        'questions': [
            {
                'question':'What is the initial vertical velocity of the ball',
                'answerValue': 'yInitSpeed', // Identifies the answer referring to the dataGiven object above.
                'id':'getYVelocity' // Relates the entered answer to the variable above.
            }
        ]
    }
];

answersSubmitted() {

    this.questionBank[0].questions.forEach(question => {

        var value = parseFloat(this.formAnswers.value[question.id]);

        if(question.answerValue === 'xInitSpeed') {
          if(this.percentageWithinBounds(value, this.valueInitialSpeed.x, this.tolerance)) {
            this.correctAnswer(question);
          }
        } else if(question.answerValue === 'yInitSpeed') {
          if(this.percentageWithinBounds(value, this.valueInitialSpeed.y, this.tolerance)) {
            this.correctAnswer(question);
          }
        } else {}// if{} ... etc etc
        
    });
}

private percentageWithinBounds(x, y, z) {
    // Currently not applicable.
}

private correctAnswer(x) {
    // Currently not applicable.
}
                    

I believe some adjustments might be needed in the questionBank array to accommodate this improvement. I am open to modifications to simplify the process for future use and to enhance more complex simulations down the line.

Answer №1

It seems like you may be making things more complicated for yourself by returning a variable that points to an answer instead of directly returning the answer itself.

https://example.com/edit/code-sample

I have simplified the process by incorporating the answer as a property of the question.

If you require more complexity, you can transform answer into a function that computes the appropriate value, similar to this example:

https://example.com/edit/another-code-sample

You are free to implement any desired logic within the answer function, such as taking in the given answer and returning true or false based on specific conditions.

A few additional comments have been provided regarding minor issues. I strongly suggest enabling noImplicitAny in your tsconfig.json file - it promotes explicit typing. After all, why use Typescript if you're not leveraging its type system? Types are meant to assist you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with making sequential requests in Angular using RxJS

I am in need of assistance with the following functions; public userLogin(username: string, password: string) { return this.http.post<any>(`${this.apiURL}/login `, {username, password}, constants.httpOptions) .pipe( map((response) ...

I need assistance in deactivating all functions activated by @typescript-eslint/ban-types

I am constantly battling with the "@typescript-eslint/ban-types" rule. It plagues me with countless errors in the hundreds on my large project, making it a nightmare to manage and resolve. Despite having the following configuration in place, eslint seems ...

making GET and POST requests within a single function using Angular 2

How can I trigger an HTTP POST service call after a successful GET response? This is how I've implemented the GET call: import {Page, NavController} from 'ionic-angular'; import {Http, Headers} from 'angular2/http'; import ' ...

Defining the signature of an unnamed function in TypeScript

Within my Express code, I have an anonymous function set up like this: app.use((err, req, res, next) => { // ... }); I am looking to specify the type of the function as ErrorRequestHandler (not the return type). One way to achieve this is by defining ...

The Angular 5 route guard on a component-less route does not successfully redirect

My current challenge involves setting up a component-less route with a route guard in Angular 5. Here is my code snippet: const routes: Routes = [ {path: '', runGuardsAndResolvers: 'always', canActivateChild:[AppRouteGuard], children: ...

What is preventing Typescript from utilizing the includes function for arrays?

I understand that Typescript is based on ES6 or ES2015. However, I'm confused because anArray.includes('ifExist'); is only available in ES6. Even though I'm using Typescript, why am I unable to use it? The error message says that anAr ...

Creating an application using AngularJS 4 and the Express generator

Recently, I successfully created a basic angular 4 application using this helpful tutorial: https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli My next challenge is integrating the angular 4 app with an express application generated b ...

Learn the method for triggering events with a strongly-typed payload in Vue 3 Composition API and TypeScript

I'm currently exploring Vue 3 Composition API along with TypeScript, particularly focusing on emitting events with a strictly typed payload. There's an example provided below, but I'm unsure if it's the most effective way to achieve t ...

Guide to embedding a Java-script file within an Angular component.ts Type-script file and triggering the onClick function for a MEAN stack application

import { Component } from '@angular/core'; import * as e from 'cors'; declare function click_fun():any; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./re ...

While attempting to send a GET Request in Angular, access to XMLHttpRequest has been denied due to CORS policy restrictions

I am attempting to establish a GET method for my PHP API. Here is the code snippet I am using: export class PerfilComponent { perfil: any; constructor(private http: HttpClient) { } ngOnInit() { const token:string | null = localStorage.getItem(&ap ...

waiting for the import statement in a React/NextJS/Typescript project to resolve

While working on my node.js development server, I encountered a problem with the following code: import { useRouter } from 'next/router' import nextBase64 from 'next-base64'; const Load = () => { const router = useRouter() co ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

Error encountered in Typescript function wrapper: The provided data type of number[] cannot be assigned to [number]

Within this code snippet, the function requires two arguments: one for the function that needs to be wrapped and another for the argument producer. function wrapper<K extends Array<any>, T>(fn: (...args: K) => T, pd: (...args: any) => K): ...

Best practices for interacting with a REST API using Angular

I am currently working on a web Angular app where in globalservice.ts I have defined basepath:string = "https://myapi.com/api/v2/". I need to retrieve data from this API. To achieve this, I have included the following code snippet in server.js. Any recomme ...

Responsive Bootstrap card - automatically adjust width to fit the child content

Consider the code snippet below: <div class="container-fluid"> <div class="row pt-3"> <div class="col-lg-4 d-flex flex-column align-items-center"> <div class="card"> <di ...

Mastering the utilization of custom input events in PrimeNG with Angular

I am currently working on an Angular 16 project. Within this project, I have implemented a number input field that is being validated using formControls. To make my work more efficient, especially since this input is used frequently, I decided to encapsula ...

Error in Angular: A ReferenceError has occurred stating that the bootstrap is not defined

I'm having trouble understanding why the error persists even though I've declared Bootstrap and confirmed it's defined when debugging. Does anyone have any insights on why this might be happening? Could it be related to Bootstrap? Here is t ...

Encountering the Selenium Webdriver HTTP error within an Angular 4 project

ERROR Detected Issue found in: ./node_modules/selenium-webdriver/http/index.js Module not found: Error: Unable to locate 'http' in 'C:\Users\aprajita.singh\Documents\Angular 4\Auto-Trender-Project\node_modules ...

Make sure the static variable is set up prior to injecting the provider

In our Angular6 application, we utilize a globalcontextServiceFactory to initialize the application before rendering views. This process involves subscribing to get configuration from a back-end endpoint and then using forkJoin to retrieve environment app ...

"Is it possible to disable the transition animation in mat-sidenav of Angular Material without affecting the animations of

My Angular application features a mat-sidenav that is organized like this: <mat-sidenav-container> <mat-sidenav [mode]="'side'"> <!-- Sidenav content --> </mat-sidenav> <mat-sidenav-content ...