Math.abs for string literal type in TypeScript

Example of Absolute use
Example of Absolute use

Today we discuss Absolute

To return a number here is a very complicated task because a number of iterations is limited (if we try to solve it with arrays). Instead we can use string literals and return a string as a result.

Here we go 🚀

Return result for the string

If we have a string, and we know that there's a number in it, we can check for a minus sign at the beginning:

Positive in case we have negative
Positive in case we have negative

Otherwise, we return the same string as we expect it to be positive

https://tsplay.dev/WKko8W

Return result for the number and bigint

Still we return the same number or bigint if we pass it to Absolute

As we already can manipulate numbers in a string, let's put a number to a string:

Put number and bigint into a string
Put number and bigint into a string

And now all the tests are passed ✅ – https://tsplay.dev/WJ9oRm

Good night ⛈🌙

typescript

Alexey Berezin

Senior Software Engineer, UK Global Talent 🇬🇧

The portrait photo of me

Thank you for reading my blog post! If you have any questions, suggestions, or just want to say hi, feel free to reach out in social networks, or via email. I would love to hear from you!

Comments