Search code examples
node.jssonarqube

define a constant instead of duplicating 5 times


I'm fairly new to Node.js and I am having some issues. I received error in sonarqube as define a constant instead of duplicating 5 times for "-deleteFlag". how can i resolved this issue.

export class CCGuid {
  "-deleteFlag": string;
  "#text": string;

  constructor(obj: any) {
    if (typeof obj === "string") {
      this["#text"] = obj;
      this["-deleteFlag"] = "N";
    } else {
      try {
        this["-deleteFlag"] = obj["-deleteFlag"];
      } catch {
        this["-deleteFlag"] = undefined;
      }
      try {
        this["#text"] = obj["#text"];
      } catch {
        this["#text"] = undefined;
      }
    }
  }
}

Solution

  • export class CCGuid {
      "-deleteFlag": string;
      "#text": string;
    
      constructor(obj: any) {
        const deleteFlag = "-deleteFlag";
        if (typeof obj === "string") {
          this["#text"] = obj;
          this[deleteFlag] = "N";
        } else {
          try {
            this[deleteFlag] = obj[deleteFlag];
          } catch {
            this[deleteFlag] = undefined;
          }
          try {
            this["#text"] = obj["#text"];
          } catch {
            this["#text"] = undefined;
          }
        }
      }
    } 
    

    I think this should do the trick with SQ, at least when it comes to that particular variable. You can do the same with "#text" of course.


    After edit: sorry my first answer was broken, I was in a rush and didn't realize what I was really writing down.

    Given my updated snippet, you can do the following:

    this[deleteFlag']: This will work.

    this['-deleteFlag']: This will of course work but Sonar Qube will complain because your use of duplicated string literals.

    this.deleteFlag: This won't work because would be looking for a deleteFlag key on the object. Such key doesn't exist, it's '-deleteFlag'.

    this['deleteFlag']: this is functionally the same as the line above. Would look for a 'deletFlag' key on the object, which doesn't exist.

    Sorry for the confusion! Hope this helps now