Skip to content

Commit

Permalink
Merge pull request #220 from gilligan/add-reverse
Browse files Browse the repository at this point in the history
Add S.reverse
  • Loading branch information
davidchambers committed May 27, 2016
2 parents aa46d68 + 41562c9 commit 8ef03e0
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
22 changes: 22 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2460,6 +2460,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',
Expand Down
43 changes: 43 additions & 0 deletions test/reverse.js
Original file line number Diff line number Diff line change
@@ -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');
});

});

0 comments on commit 8ef03e0

Please sign in to comment.