@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
90 lines (89 loc) • 2.85 kB
JavaScript
import { toEnsuredNumber } from '../number/number-conversion.js';
/**
* Suffix for {@link addPercent} and {@link removePercent}.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export const percentSuffix = '%';
/**
* Suffix for {@link addPx} and {@link removePx}.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export const pxSuffix = 'px';
/**
* Adds the `'px'` suffix to a string if it does not already exist.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function addPx(input) {
return addSuffix({ value: input, suffix: pxSuffix });
}
/**
* Removes the `'px'` suffix from a string if it exists.
*
* @category String
* @category Package : @augment-vir/common
* @throws `TypeError` if the input can't be converted into a number.
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function removePx(input) {
return toEnsuredNumber(removeSuffix({ value: input, suffix: pxSuffix }));
}
/**
* Adds the `'%'` suffix to a string if it does not already exist.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function addPercent(input) {
return addSuffix({ value: input, suffix: percentSuffix });
}
/**
* Removes the `'%'` suffix from a string if it exists.
*
* @category String
* @category Package : @augment-vir/common
* @throws `TypeError` if the input can't be converted into a number.
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function removePercent(input) {
return toEnsuredNumber(removeSuffix({ value: input, suffix: percentSuffix }));
}
/**
* Adds a suffix to a string if it does not already exist.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function addSuffix({ value, suffix, }) {
if (String(value).endsWith(suffix)) {
return String(value);
}
else {
return `${String(value)}${suffix}`;
}
}
/**
* Removes a suffix from a string if it exists.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function removeSuffix({ value, suffix, }) {
if (value.endsWith(suffix)) {
return value.slice(0, Math.max(0, value.length - suffix.length));
}
else {
return value;
}
}