Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add S.length function #159

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,14 @@
}
);

// Countable :: TypeClass
var Countable = $.TypeClass(
'sanctuary/Countable',
function(x) {
return x != null && x.length != null && $.Integer.test(x.length);
}
);

// Foldable :: TypeClass
var Foldable = $.TypeClass(
'sanctuary/Foldable',
Expand Down Expand Up @@ -1951,6 +1959,27 @@

//. ### List

//# length :: Semigroup a => a -> Int
//.
//. Returns the number of elements of any Countable: members of this
//. type class expose a `length` property of type Integer.
//.
//. ```javascript
//. > S.length([1, 2, 3, 4, 5])
//. 5
//.
//. > S.length('abcdef')
//. 6
//.
//. > S.length(function(a, b) { return a + b; })
//. 2
//. ```
S.length =
def('length',
{a: [Countable]},
[a, $.Integer],
function(x) { return x.length; });

//# slice :: Integer -> Integer -> [a] -> Maybe [a]
//.
//. Returns Just a list containing the elements from the supplied list
Expand Down
23 changes: 23 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2683,6 +2683,29 @@ describe('logic', function() {

describe('list', function() {

describe('length', function() {

it('is a unary function', function() {
eq(typeof S.length, 'function');
eq(S.length.length, 1);
});

it('type checks its arguments', function() {
assert.throws(function() { S.length(1); },
errorEq(TypeError,
'‘length’ requires ‘a’ to implement Countable; ' +
'Number and FiniteNumber and NonZeroFiniteNumber ' +
'and Integer and ValidNumber do not'));
});

it('returns the length of a Countable', function() {
eq(S.length([1, 2, 3, 4, 5]), 5);
eq(S.length('abcdef'), 6);
eq(S.length(function(a, b) { return a + b; }), 2);
});

});

describe('at', function() {

it('is a binary function', function() {
Expand Down