froebel
Version:
TypeScript utility library
18 lines (17 loc) • 579 B
JavaScript
import { assert } from "./except.mjs";
/**
* Surrounds the `str` with `surrounding`. `surrounding` must have an even length.
*
* @example
* ```
* surround("foo", "()") // "(foo)"
* surround("foo", "({[]})") // "({[foo]})"
* ```
*/
export const surround = (str, surrounding) => {
if (typeof surrounding !== "string") return str;
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)}`;
};
export default surround;