Skip to content

Commit

Permalink
Implemented functionality
Browse files Browse the repository at this point in the history
Signed-off-by: Jaid <[email protected]>
  • Loading branch information
Jaid committed Feb 16, 2019
1 parent 1036d3e commit 9d3cadf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
28 changes: 14 additions & 14 deletions src/index.js
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
}
14 changes: 12 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,20 @@ const {default: ensureEnd} = require(indexModule)

it("should run for string", () => {
const result = ensureEnd("cd", "ab")
expect(result).toEqual("abcd")
expect(result).toEqual("cdab")
})

it("should run for arrays", () => {
const result = ensureEnd(["c", "d"], ["a", "b"])
expect(result).toEqual(["a", "b", "c", "d"])
expect(result).toEqual(["c", "d", "a", "b"])
})

it("should not falsely run for string", () => {
const result = ensureEnd("hello!", ["!"])
expect(result).toEqual("hello!")
})

it("should not falsely run for arrays", () => {
const result = ensureEnd(["c", "d"], ["d"])
expect(result).toEqual(["c", "d"])
})

0 comments on commit 9d3cadf

Please sign in to comment.