-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Jaid <[email protected]>
- Loading branch information
Showing
2 changed files
with
26 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,37 +1,37 @@ | ||
/** @module ensure-end */ | ||
|
||
import {isEqual, take} from "lodash" | ||
import {isEqual, takeRight} from "lodash" | ||
|
||
/** | ||
* Ensures that a string or an array starts with specified value | ||
* Ensures that a string or an array ends with specified value | ||
* @example | ||
* import ensureEnd from "ensure-end" | ||
* ensureEnd("cd", "ab") | ||
* // "abcd" | ||
* // "cdab" | ||
* @example | ||
* import ensureEnd from "ensure-end" | ||
* ensureEnd(["ab"], ["c", "d"]) | ||
* // ["c", "d", "ab"] | ||
* // ["ab", "c", "d"] | ||
* @function | ||
* @param {string|array} value String or array that should start with specified value | ||
* @param {string|array} ensuredStart The wanted start value | ||
* @param {string|array} value String or array that should end with specified value | ||
* @param {string|array} ensuredEnd The wanted end value | ||
* @returns {*} Cleaned value | ||
*/ | ||
export default (value, ensuredStart) => { | ||
export default (value, ensuredEnd) => { | ||
if (typeof value === "string") { | ||
if (value.startsWith(ensuredStart)) { | ||
if (value.endsWith(ensuredEnd)) { | ||
return value | ||
} | ||
return `${ensuredStart}${value}` | ||
return `${value}${ensuredEnd}` | ||
} | ||
if (Array.isArray(value, ensuredStart)) { | ||
if (!Array.isArray(ensuredStart)) { | ||
ensuredStart = [ensuredStart] | ||
if (Array.isArray(value)) { | ||
if (!Array.isArray(ensuredEnd)) { | ||
ensuredEnd = [ensuredEnd] | ||
} | ||
if (isEqual(take(value, ensuredStart.length), ensuredStart)) { | ||
if (isEqual(takeRight(value, ensuredEnd.length), ensuredEnd)) { | ||
return value | ||
} | ||
return [...ensuredStart, ...value] | ||
return [...value, ...ensuredEnd] | ||
} | ||
return value | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters