beraliv

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

Comments

Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter