Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 6fd533f

Browse files
sosmaniac-FCCKent C. Dodds
authored and
Kent C. Dodds
committed
feat(common): add truncate function with tests (#165)
1 parent ac7c97d commit 6fd533f

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

src/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import dec2bin from './dec2bin'
3232
import searchAndReplace from './search-and-replace'
3333
import sqrt from './sqrt'
3434
import toPower from './to-power'
35+
import truncate from './truncate'
3536
import mod from './mod'
3637
import shallowEqual from './shallow-equal'
3738
import swapCase from './swap-case'
@@ -94,6 +95,7 @@ export {
9495
searchAndReplace,
9596
sqrt,
9697
toPower,
98+
truncate,
9799
mod,
98100
shallowEqual,
99101
swapCase,

src/truncate.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export default truncate
2+
3+
/**
4+
* Original Source: https://stackoverflow.com/questions/1301512/truncate-a-string-straight-javascript
5+
* This method will perserve a specified amount of starting characters and delete the rest
6+
* @param {String} target - the string to truncate
7+
* @param {Number} length - the amount of saved characters prior to truncation
8+
* @return {String} - the truncated string
9+
*/
10+
11+
function truncate(target, length) {
12+
if (target.length <= length) {
13+
return target
14+
}
15+
return `${target.toString().substring(0, length)}...`
16+
}

test/truncate.test.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import test from 'ava'
2+
import {truncate} from '../src'
3+
4+
test('string truncates by the indicated length', t => {
5+
const toTrunc = 'This is a long sentence that needs to be truncated'
6+
const index = 15
7+
const expected = 'This is a long ...'
8+
const actual = truncate(toTrunc, index)
9+
t.deepEqual(actual, expected)
10+
})
11+
12+
test('string does not truncate due to its small size', t => {
13+
const toTrunc = 'Short phrase'
14+
const index = 15
15+
const expected = 'Short phrase'
16+
const actual = truncate(toTrunc, index)
17+
t.deepEqual(actual, expected)
18+
})

0 commit comments

Comments
 (0)