Skip to content

Commit

Permalink
feat(#117): finish NumerifyString<S>
Browse files Browse the repository at this point in the history
  • Loading branch information
ashgw committed Apr 26, 2024
1 parent 25d5cd4 commit b025d57
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
3 changes: 2 additions & 1 deletion dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ Vals
Immutate
roids
Nums
Nand
Nand
Numerify
16 changes: 15 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export type IsPositiveFloat<F extends Numeric> = IsPositive<Float<F>>;
*/
export type IsOdd<T extends Numeric> = IfExtends<
StringifyNum<T>,
`${number | ''}${1 | 3 | 5 | 7 | 9}`,
`${Numeric | ''}${1 | 3 | 5 | 7 | 9}`,
true,
false
>;
Expand Down Expand Up @@ -568,6 +568,20 @@ export type EitherOneOrMany<T> = T | T[];
*/
export type StringifyNum<N extends Numeric> = `${N}`;

/**
* Turn a given string literal to a numeric
* @example
* ````ts`
NumerifyString<'54'>; // 54
NumerifyString<'699620.000000001'>; // 699620.000000001
IsNegativeFloat<NumerifyString<'-699620.000000001'>>; // true
* ````
*/
export type NumerifyString<S extends string> = S extends `${infer N extends
Numeric}`
? N
: never;

/**
* Get the absolute value of a numeric N
* @example
Expand Down
43 changes: 43 additions & 0 deletions tests/numerify-string.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { NumerifyString, TestType, IsNegativeFloat } from 'src';
import { test, expect } from 'vitest';

test('_', () => {
const result: TestType<NumerifyString<'54'>, 54, true> = true;
expect(result).toBe(true);
});

test('_', () => {
const result: TestType<
NumerifyString<'69962000000000'>,
69962000000000,
true
> = true;
expect(result).toBe(true);
});

test('works with floats as well', () => {
const result: TestType<
NumerifyString<'699620.000000001'>,
699620.000000001,
true
> = true;
expect(result).toBe(true);
});

test('works with negative floats as well', () => {
const result: TestType<
IsNegativeFloat<NumerifyString<'-699620.000000001'>>,
true,
true
> = true;
expect(result).toBe(true);
});

test('works with negative floats as well', () => {
const result: TestType<
NumerifyString<'-699620.000000001'>,
-699620.000000001,
true
> = true;
expect(result).toBe(true);
});

0 comments on commit b025d57

Please sign in to comment.