The switch statement and corresponding if-else loop consistently produce incorrect results

I'm currently facing an issue where I need to display different icons next to documents based on their file types using Angular framework. However, no matter what file type I set as the fileExtension variable (e.g., txt or jpg), it always defaults to returning file-text as the iconType.

    public getIcon(document: Document): string {
        let mimeType = document.fileType;
        let fileExtension = mimeType.split('.')[1];
        let iconType = '';

        switch (fileExtension) {
            case fileExtension === 'jpeg' || 'gif' || 'png' || 'svg' || 'xml'  || 'bmp' || 'jpg'|| 'tif' || 'tiff':
                iconType = 'picture';
                break;
            case fileExtension === 'avi' || 'mpg' || 'wmv' || 'mpeg' || 'mp4' || 'mov':
                iconType = 'video-folder';
                break;
            case fileExtension === 'cda' || 'mp3' || 'mpa' || 'wav' || 'wma':
                iconType = 'volume';
                break;
            case fileExtension === 'pdf' || 'ai' || 'pptx':
                iconType = 'article';
                break;
            default:
                //includes: .docx , .odt, .rtf, .txt, .xml, .xps
                iconType = 'file-text';
                break;
        }
        console.log(iconType);
        return iconType;
    }

Despite setting fileExtension to be "jpg", it always returns the default icon-type of "file-text" upon debugging. Debugging with breakpoints can be seen here.

I also attempted a simple if-else loop approach, but it still returned the first if case value for all scenarios (e.g.: picture even when fileExtension is "txt"):

        if (fileExtension === 'jpeg' || 'gif' || 'png' || 'svg' || 'xml' || 'bmp' || 'jpg' || 'tif' || 'tiff') {
            iconType = 'picture';
        } else if (fileExtension === 'avi' || 'mpg' || 'wmv' || 'mpeg' || 'mp4' || 'mov') {
            iconType = 'video-folder';
        } else if (fileExtension === 'cda' || 'mp3' || 'mpa' || 'wav' || 'wma') {
            iconType = 'volume';
        } else if (fileExtension === 'pdf' || 'ai' || 'pptx') {
            iconType = 'article';
        } else {
            iconType = 'file-text';
        }
        console.log(iconType);
        return iconType;

I am quite perplexed as to why it does not enter the correct case. Any assistance would be highly appreciated!

Answer №1

To ensure accuracy, remember to reiterate the left side of your conditional check within each if statement; alternatively, consider creating separate cases for each unique file extension type in your switch.

if(fileExtension === “jpg” || fileExtension === “png” …) {…}

If you are looking for additional approaches, here are some alternatives:

Utilize an array to store each picture type and then verify if the value is present in the array:

pictureFileExtensions = [“jpg”, “gif”, …]
videoFileExtensions = […]

If (pictureFileExtension.includes(fileExtension)){
        iconType = “picture”
    } else if (videoFileExtension.includes(fileExtension)){
        iconType = “video”
    } else if …

Another option is to create an object with the file extension as the key and the corresponding icon type as the value:

const iconTypes = {jpg: “picture”, avi: “video”, …}

iconType = iconType[fileExtension]

Answer №2

You might want to reconsider how you're utilizing the switch case statement. The correct syntax is as follows:

    switch (fileExtension) {
        case 'jpeg':
        case 'gif':
        case 'png':
        case 'svg':
        case 'xml':
        case 'bmp':
        case 'jpg':
        case 'tif':
        case 'tiff':
            iconType = 'picture';
            break;
        case 'avi':
        case 'mpg':
        case 'wmv':
        case 'mpeg':
        case 'mp4':
        case 'mov':
            iconType = 'video-folder';
            break;
        case 'cda':
        case 'mp3':
        case 'mpa':
        case 'wav':
        case 'wma':
            iconType = 'volume';
            break;
        case 'pdf':
        case 'ai':
        case 'pptx':
            iconType = 'article';
            break;
        default:
            //includes: .docx , .odt, .rtf, .txt, .xml, .xps
            iconType = 'file-text';
            break;
    }

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

Switching Modes in Angular Application - Going from Demo Mode to App Mode?

Working on an Angular application, I have encountered a unique scenario that requires a solution. Our application, test.com, utilizes several restful APIs developed by us. Our business now wants us to store dummy responses from these APIs in static JSON f ...

What is the best way to convert a tuple containing key/value pairs into an object?

How can the function keyValueArrayToObject be rewritten in order to ensure that the type of keyValueObject is specifically {a: number; b: string}, instead of the current type which is {[k: string]: any}? const arrayOfKeyValue = [ {key: 'a', val ...

Obtain the filter criteria within the user interface of a Kendo grid

My Kendo grid looks like this: <kendo-grid [data]="gridData" [pageSize]="state.take" [skip]="state.skip" [sort]="state.sort" [filter]="state.filter" filterable="menu" (dataStateChange)="dataStateChange($event)" > In the ...

Utilize Angular 4 Router to intercept every router modification

I want to implement a Breadcrumb feature. More about Breadcrumbs on Wikipedia To achieve this, I am considering creating a Service to manage it. However, I need a way to monitor any router state changes automatically, without having to add an onActivate ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

Switch from Gulp-TSLint to Gulp-ESLint for enhanced code analysis!

I am currently in the process of updating a Gulp task that uses gulp-tslint to now use gulp-eslint. The code snippet below outlines the changes I need to make: const { src } = require('gulp'); const config = require('./config'); const ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Unexpected lack of tree shaking in Angular AOT compiled application

I am developing a module called MyCommonModule that consists of common components, services, etc. This module is designed to be shared across multiple Angular applications. Here is an example of a basic app that imports MyCommonModule, without directly re ...

There are no imports in index.js and there is no systemjs configuration set up

After creating a fresh Angular project using ng new some-name, I noticed that the generated index.html file does not include any <script> tags and there is no SystemJS configuration either. Is this the expected behavior? I was anticipating the CLI ...

ViewChild with the focus method

This particular component I'm working on has a hidden textarea by default : <div class="action ui-g-2" (click)="toggleEditable()">edit</div> <textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea f ...

TypeORM - Establishing dual Foreign Keys within a single table that point to the identical Primary Key

Currently, I am working with TypeORM 0.3.10 on a project that uses Postgres. One issue I encountered is while trying to generate and execute a Migration using ts-node-commonjs. The problem arises when two Foreign Keys within the same table are referencing ...

Is there a way to ensure that fields in a sub component are validated whenever we attempt to switch the Tab using a route

Hi there, I could really use your assistance. I've done some research, but I haven't been able to find a suitable solution for my problem. I have this shared component that contains the following code which enables tab navigation through various ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

Angular2 implementation of scroll spy feature for CKEditor

I have a file loaded in CKEditor with a side menu located outside the editor. I'm looking to dynamically highlight specific items in the side navigation as different sections of the document are scrolled through. details.component.ts focusFunction() ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

Displaying a component inside a different component

I'm attempting to display components inside another component, but even when I try to include div elements within the component, they don't show up. const DisplayComponent = () => { return ( <div> <DisplayContent ...

tips for choosing an entire group in ng-select with Angular

I am implementing a multi-select dropdown with groups in Angular using the ng-select component. My goal is to allow users to select an entire group and have all items within that group automatically selected as well. I have been attempting to model my cod ...