Skip to content

Commit

Permalink
feat(digitsEnToFa): add error handling and clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
Masoud authored and Masoud committed Mar 13, 2021
1 parent d1b8faf commit 8a23631
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
13 changes: 8 additions & 5 deletions src/modules/digits/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,19 @@ const arNums = "٠١٢٣٤٥٦٧٨٩";
* Persian digits
*
*/
export function digitsEnToFa(str?: number | string): string | undefined {
if (!str) return;
export function digitsEnToFa(value?: number | string): string {
if (typeof value !== "number" && typeof value !== "string") {
throw new TypeError("the input must be string or number");
}

let string = typeof value === "number" ? String(value) : value;

let result = "" + str;
for (let i = 0; i < 10; i++) {
const replaceEntoFa = new RegExp("" + i, "g");
result = result.replace(replaceEntoFa, faNums[i]);
string = string.replace(replaceEntoFa, faNums[i]);
}

return result;
return string;
}

/** digitsFaToEn
Expand Down
15 changes: 13 additions & 2 deletions test/digits.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,19 @@ describe("Digits", () => {
expect(digitsEnToFa("123۴۵۶")).toEqual("۱۲۳۴۵۶");
expect(digitsEnToFa("٤٥٦")).toEqual("٤٥٦");
expect(digitsEnToFa("123۴۵۶")).toEqual("۱۲۳۴۵۶");
expect(digitsEnToFa()).toBeUndefined();
expect(digitsEnToFa("")).toBeUndefined();
try {
//@ts-ignore
digitsEnToFa()
}catch (e) {
expect(e.message).toEqual('the input must be string or number')
}

try {
//@ts-ignore
digitsEnToFa(undefined)
}catch (e) {
expect(e.message).toEqual('the input must be string or number')
}
});

it("digitsFaToEn", () => {
Expand Down

0 comments on commit 8a23631

Please sign in to comment.