From 41562c9139b36536efd267c4220b0288ce4be26a Mon Sep 17 00:00:00 2001 From: Tobias Pflug Date: Mon, 23 May 2016 21:14:01 +0200 Subject: [PATCH] Add S.reverse --- index.js | 22 ++++++++++++++++++++++ test/reverse.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 test/reverse.js diff --git a/index.js b/index.js index cc4ed736..dc5b14c1 100644 --- a/index.js +++ b/index.js @@ -2441,6 +2441,28 @@ return n < 0 || negativeZero(n) ? Nothing() : slice(0, -n, xs); }); + //# reverse :: [a] -> [a] + //. + //. Returns the elements of the given list in reverse order. + //. + //. ```javascript + //. > S.reverse([1, 2, 3]) + //. [3, 2, 1] + //. + //. > S.reverse('abc') + //. 'cba' + //. ``` + S.reverse = + def('reverse', + {}, + [List(a), List(a)], + function reverse(xs) { + if (_type(xs) === 'String') return reverse(xs.split('')).join(''); + var result = []; + for (var idx = xs.length - 1; idx >= 0; idx -= 1) result.push(xs[idx]); + return result; + }); + // ArrayLike :: TypeClass var ArrayLike = $.TypeClass( 'ArrayLike', diff --git a/test/reverse.js b/test/reverse.js new file mode 100644 index 00000000..96a9cb34 --- /dev/null +++ b/test/reverse.js @@ -0,0 +1,43 @@ +'use strict'; + +var throws = require('assert').throws; + +var eq = require('./utils').eq; +var errorEq = require('./utils').errorEq; +var S = require('..'); + + +describe('reverse', function() { + + it('is a unary function', function() { + eq(typeof S.reverse, 'function'); + eq(S.reverse.length, 1); + }); + + it('type checks its arguments', function() { + throws(function() { S.reverse({answer: 42}); }, + errorEq(TypeError, + 'Invalid value\n' + + '\n' + + 'reverse :: List a -> List a\n' + + ' ^^^^^^\n' + + ' 1\n' + + '\n' + + '1) {"answer": 42} :: Object, StrMap Number, StrMap FiniteNumber, StrMap NonZeroFiniteNumber, StrMap Integer, StrMap ValidNumber\n' + + '\n' + + 'The value at position 1 is not a member of ‘List a’.\n')); + + }); + + it('reverses arrays', function() { + eq(S.reverse([]), []); + eq(S.reverse([1, 2, 3]), [3, 2, 1]); + eq(S.reverse(['1', '2', '3']), ['3', '2', '1']); + }); + + it('reverses strings', function() { + eq(S.reverse(''), ''); + eq(S.reverse('123'), '321'); + }); + +});