Skip to content

Commit

Permalink
chore(string): instantiation limiters
Browse files Browse the repository at this point in the history
  • Loading branch information
millsp committed Mar 10, 2021
1 parent 80579e1 commit 9a678d8
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 13 deletions.
16 changes: 9 additions & 7 deletions sources/String/Join.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import {Tail} from '../List/Tail'
import {List} from '../List/List'
import {Literal} from './_Internal'
import {Length} from '../List/Length'
import {Cast} from '../Any/Cast'

/**
* @hidden
*/
type _Join<T extends List<Literal>, D extends string, S extends string = ''> =
T extends [Literal]
? `${S}${T[0]}`
: _Join<Tail<T>, D, `${S}${T[0]}${D}`>
type _Join<T extends List, D extends string> =
T extends [] ? '' :
T extends [Literal] ? `${T[0]}` :
T extends [Literal, ...infer R] ? `${T[0]}${D}${_Join<R, D>}` :
string

/**
* Concat many literals together
* @param T to concat
* @param D to delimit
*/
export type Join<T extends List<Literal>, D extends string = ''> =
T extends [] ? '' : number extends Length<T> ? string : _Join<T, D>
_Join<T, D> extends infer X
? Cast<X, string>
: never
15 changes: 12 additions & 3 deletions sources/String/Replace.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import {Cast} from '../Any/Cast'
import {Literal} from './_Internal'

/**
* @hidden
*/
type _Replace<S extends string, R extends Literal, W extends Literal> =
S extends `${infer BS}${R}${infer AS}`
? Replace<`${BS}${W}${AS}`, R, W>
: S

/**
* Replace `R` with `W` in `S`
* @param S
* @param R
* @param W
*/
export type Replace<S extends string, R extends Literal, W extends Literal> =
S extends `${infer BS}${R}${infer AS}`
? Replace<`${BS}${W}${AS}`, R, W>
: S
_Replace<S, R, W> extends infer X
? Cast<X, string>
: never
15 changes: 12 additions & 3 deletions sources/String/Split.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import {Cast} from '../Any/Cast'
import {Pop} from '../List/Pop'

/**
* @ignore
*/
type _Split<S extends string, D extends string, T extends string[] = []> =
type __Split<S extends string, D extends string, T extends string[] = []> =
S extends `${infer BS}${D}${infer AS}`
? _Split<AS, D, [...T, BS]>
? __Split<AS, D, [...T, BS]>
: [...T, S]

/**
* @hidden
*/
type _Split<S extends string, D extends string = ''> =
D extends '' ? Pop<__Split<S, D>> : __Split<S, D>

/**
* Split `S` by `D` into a [[List]]
* @param S to split up
* @param D to split at
*/
export type Split<S extends string, D extends string = ''> =
D extends '' ? Pop<_Split<S, D>> : _Split<S, D>
_Split<S, D> extends infer X
? Cast<X, string[]>
: never

0 comments on commit 9a678d8

Please sign in to comment.