Skip to content

Instantly share code, notes, and snippets.

@dennisseah
Created January 20, 2020 15:50
Show Gist options
  • Save dennisseah/e612b2f72c80a15c4dd853a959ba8ec3 to your computer and use it in GitHub Desktop.
Save dennisseah/e612b2f72c80a15c4dd853a959ba8ec3 to your computer and use it in GitHub Desktop.
Observations on Typescipt implementation

0. Avoid using any and object type

Using any or object types resulted in no type checking. Typescipt is used because we want type checking :-).

1. Use Helper Function

Whenever we copy and paste some code snippet, it is a signal to us that we need helper function. Example

if (value1 === undefined || value1 === null || value1 === "") {
    console.error("value is missing");
}
if (value2 === undefined || value2 === null || value2 === "") {
    console.error("value is missing");
}
if (value3 === undefined || value3 === null || value3 === "") {
    console.error("value is missing");
}
...

can be

const printErrorWhenValueIsMissing = (val: string | undefined || null) => {
  if (val === undefined || val === null || val === "") {
    console.error("value is missing");
  }
}

printErrorWhenValueIsMissing(value1);
printErrorWhenValueIsMissing(value2);
printErrorWhenValueIsMissing(value3);
...

2. Async function

Create async function only went it is need. Having sync for non async function resulted in creation of Promise object which is not needed.

3. Use Array.prototype.join to simplify code

Example

    let str = "";
    clusters.forEach(cluster => {
      str += cluster + ", ";
    });
    str = str.substr(0, str.length - 2);

can be

    const str = clusters.join(", ");

4. Use map function to simplify code

Example

  const clusters: string[] = [];
  if (tags) {
    tags.forEach((itag: ITag) => {
      clusters.push(itag.name);
    });
  }

can be

  const clusters: string[] = tags ? tags.map(tag => tag.name) : [];

5. Use filter function to simplify code

Example

const clusters: ICluster[] = [];
if (status) {
  status.forEach((stat: ICluster) => {
    if (manifestCommitId === stat.commit) {
      clusters.push(stat);
    }
  });
}
return clusters;

can be

return (status || []).filter(
  stat => manifestCommitId === stat.commit
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment