I have created an Angular pipe to suppress the sensitive information like credit cards, bank account, ABA numbers etc.
This is working fine but I would like to know if this is the best possible way to implement the logic.
Here is the Typescript code for pipe logic.
export class SuppressInfoPipe implements PipeTransform {
transform(valueToSupress: string, unSuppressedCount?: number): string {
let suppressedOutput = '';
const valueToRemainUnsuppressed =
valueToSupress.substring(valueToSupress.length - unSuppressedCount, valueToSupress.length);
let astariskLength = valueToSupress.length - unSuppressedCount;
for ( let i = 0; i < astariskLength; i++) {
suppressedOutput = suppressedOutput.concat('*');
}
suppressedOutput = suppressedOutput.concat(valueToRemainUnsuppressed);
return suppressedOutput;
}
}
it takes the string input and the number of character they will no be hidden and then return the suppressed output.
Comments and suggestions are welcomed.
1 Answer 1
I would avoid the for loop to generate the "suppressed string".
My approach would be:
export class SuppressInfoPipe implements PipeTransform {
transform(valueToSupress: string, unSuppressedCount = 0): string {
const suppressedCount = valueToSupress.length - unSuppressedCount;
const valueToRemainUnsuppressed =
valueToSupress.substring(suppressedCount, valueToSupress.length);
return Array(suppressedCount + 1).join('*') + valueToRemainUnsuppressed; // suppressedCount + 1: since join will a string of length "suppressedCount"
}
}
In this case:
Array(n) will return an array of length n.
.join("*")
will join the list and return a string equivalent of length n-1.
-
\$\begingroup\$ That's much better. Only thing I want to confirm is this changing the type of Array object when returning just like JavaScript does to variables depending upon the data being assigned ? \$\endgroup\$Muhammad Ahsan– Muhammad Ahsan2019年03月19日 11:13:10 +00:00Commented Mar 19, 2019 at 11:13
-
\$\begingroup\$ Updated my answer. \$\endgroup\$Sree.Bh– Sree.Bh2019年03月19日 11:18:44 +00:00Commented Mar 19, 2019 at 11:18
-
\$\begingroup\$ I got your point :) . Thanks for adding explanation to your answer. \$\endgroup\$Muhammad Ahsan– Muhammad Ahsan2019年03月19日 11:22:23 +00:00Commented Mar 19, 2019 at 11:22