diff --git a/src/index.js b/src/index.js index bb4fe0bb..bde9df2a 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,6 @@ import flatten from './flatten' import snakeToCamel from './snake-to-camel' +import padLeft from './pad-left' + +export {flatten, snakeToCamel, padLeft} -export {flatten, snakeToCamel} diff --git a/src/pad-left.js b/src/pad-left.js new file mode 100644 index 00000000..f3b8f1ac --- /dev/null +++ b/src/pad-left.js @@ -0,0 +1,21 @@ +export default padLeft + +/** + * Original Source: http://stackoverflow.com/a/34083277/971592 + * + * This method will pad the left of the given string by + * the given size with the given character + * + * @param {String} str - The string to pad + * @param {Number} size - The total size to pad + * @param {String} padWith - The character to use for padding + * @return {String} - The padded string + */ +function padLeft(str, size, padWith) { + if (size <= str.length) { + return str + } else { + return Array(size - str.length + 1).join(padWith || '0') + str + } +} + diff --git a/test/pad-left.test.js b/test/pad-left.test.js new file mode 100644 index 00000000..3ce3b490 --- /dev/null +++ b/test/pad-left.test.js @@ -0,0 +1,20 @@ +import test from 'ava' +import {padLeft} from '../src' + +test('pads left of the given string', t => { + const original = '123' + const expected = 'zz123' + const padLength = 5 + const padWith = 'z' + const actual = padLeft(original, padLength, padWith) + t.same(actual, expected) +}) + +test('defaults to pad a zero', t => { + const original = '123' + const expected = '00123' + const padLength = 5 + const actual = padLeft(original, padLength) + t.same(actual, expected) +}) +