diff --git a/src/index.js b/src/index.js index eae1beb2..2fa84767 100644 --- a/src/index.js +++ b/src/index.js @@ -54,6 +54,7 @@ import median from './array-median' import timeDifference from './timeDifference' import isPrime from './is-prime' import swapElements from './swapElements' +import reverse from './reverse' export { isOdd, @@ -112,4 +113,5 @@ export { timeDifference, isPrime, swapElements, + reverse, } diff --git a/src/reverse.js b/src/reverse.js new file mode 100644 index 00000000..41fe9258 --- /dev/null +++ b/src/reverse.js @@ -0,0 +1,17 @@ +export default reverse + +/** + * Original Source: https://stackoverflow.com/a/4859258/7221168 + * + * Function that recursively reverses a string + * + * @param {string} str - A string + * @return {string} - A reversed string + */ +function reverse(str) { + if (str === '') { + return str + } else { + return reverse(str.substr(1)) + str.charAt(0) + } +} diff --git a/test/reverse.test.js b/test/reverse.test.js new file mode 100644 index 00000000..48ce2b67 --- /dev/null +++ b/test/reverse.test.js @@ -0,0 +1,30 @@ +import test from 'ava' +import {reverse} from '../src' + +test('string with only letters', t => { + const str = 'abcdefG' + const expected = 'Gfedcba' + const result = reverse(str) + t.is(expected, result) +}) + +test('string with only numbers', t => { + const str = '1234567890' + const expected = '0987654321' + const result = reverse(str) + t.is(expected, result) +}) + +test('string with letters and special characters', t => { + const str = 'abc!"§…' + const expected = '…§"!cba' + const result = reverse(str) + t.is(expected, result) +}) + +test('string with only special characters', t => { + const str = 'œ∑´®†' + const expected = '†®´∑œ' + const result = reverse(str) + t.is(expected, result) +})