[Typescript] 124. Binary to Decimal
typescript to Binary Decimal 124
2023-09-14 09:00:44 时间
Implement BinaryToDecimal<S>
which takes an exact string type S
consisting 0 and 1 and returns an exact number type corresponding with S
when S
is regarded as a binary. You can assume that the length of S
is equal to or less than 8 and S
is not empty.
type Res1 = BinaryToDecimal<'10'>; // expected to be 2
type Res2 = BinaryToDecimal<'0011'>; // expected to be 3
/* _____________ Your Code Here _____________ */
type NumberToArray<T extends number, R extends 1[] = []> = R['length'] extends T ? R : NumberToArray<T, [...R, 1]>;
type GetTwice<T extends unknown[]> = [...T, ...T];
type BinaryToDecimal<S extends string, Result extends unknown[] = []> = S extends `${infer First extends number}${infer RT}`
? BinaryToDecimal<RT, [...GetTwice<Result>, ...NumberToArray<First>]>
: Result['length'];
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<BinaryToDecimal<'10'>, 2>>,
Expect<Equal<BinaryToDecimal<'0011'>, 3>>,
Expect<Equal<BinaryToDecimal<'00000000'>, 0>>,
Expect<Equal<BinaryToDecimal<'11111111'>, 255>>,
Expect<Equal<BinaryToDecimal<'10101010'>, 170>>,
]
相关文章
- [Typescript] Wrap an function with Identity function to provide clean Type API
- [Typescript] Identity function - Reverse mapped types with identity function 02
- [Typescript] Identity function pattern - Using Identity function to enforce the type 01
- [Typescript] Using Extract type until to get the value from Union type
- [Typescript] 124. Binary to Decimal
- [Typescript] 84. Medium - GetMiddleElement
- [Typescript] 54. Medium - Tuple to Nested Object
- [Typescript + React] Tip: Use generics in React to make dynamic and flexible components
- [TypeScript] Statically Type String Literals with Template Literal Types in TypeScript
- [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
- [TypeScript] Use the never type to avoid code with dead ends using TypeScript
- [Typescript] Use Function Overloads to Avoid Returning undefined
- [Typescript] 131. Extreme - Query String Parser
- [Typescript 4.9] Satisfies operator
- [Typescript] 110. Hard - Union to Tuple
- [XState + Typescript] Type XState
- [Typescript] 98. Medium - Append to object
- [Typescript] 101. Hard - Typed Get
- [Typescript] 59. Medium - InorderTraversal
- [Typescript] Tips: Turn a module into a type
- [Typescript] 34. Medium - String to Union
- [Typescript] Convert a js project to typescript
- [Typescript] Declaration Merging
- [Typescript] Construct Signatures
- [Parcel] Running TypeScript with parcel-bundler
- [RxJS] Add debug method to Observable in TypeScript