-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathsurround.ts
More file actions
30 lines (28 loc) · 795 Bytes
/
surround.ts
File metadata and controls
30 lines (28 loc) · 795 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { IsEvenLength, Surround } from "./types.ts";
import { assert } from "./except.ts";
/**
* Surrounds the `str` with `surrounding`. `surrounding` must have an even length.
*
* @example
* ```
* surround("foo", "()") // "(foo)"
* surround("foo", "({[]})") // "({[foo]})"
* ```
*/
export const surround = <A extends string, B extends string>(
str: A,
surrounding: B,
): B extends "" ? A
: IsEvenLength<B> extends true ? Surround<A, B>
: never => {
if (typeof surrounding !== "string") return str as any;
assert(
surrounding.length % 2 === 0,
"surrounding string must have even length",
);
const half = surrounding.length / 2;
return `${surrounding.slice(0, half)}${str}${
surrounding.slice(half, half * 2)
}` as any;
};
export default surround;