Skip to content

Commit

Permalink
feat: iterable/ensure
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Apr 4, 2019
1 parent cf09513 commit 3d48841
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ const ensureArrayLike = require("type/array-like/ensure");

ensureArrayLike({ length: 0 }); // { length: 0 }
ensureArrayLike("foo", { allowString: true }); // "foo"
ensureArrayLike({}); // Thrown TypeError: null is not a regular expression object
ensureArrayLike({}); // Thrown TypeError: null is not an iterable
```

---
Expand Down Expand Up @@ -356,6 +356,18 @@ isIterable("foo"); // false
isIterable("foo", { allowString: true }); // true
```

#### `iterable/ensure`

If given argument is an iterable, it is returned back. Otherwise `TypeError` is thrown.

```javascript
const ensureIterable = require("type/iterable/ensure");

ensureIterable([]); // []
ensureIterable("foo", { allowString: true }); // "foo"
ensureIterable({}); // Thrown TypeError: null is not a iterable
```

---

### Date
Expand Down
9 changes: 9 additions & 0 deletions iterable/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"use strict";

var resolveException = require("../lib/resolve-exception")
, is = require("./is");

module.exports = function (value/*, options*/) {
if (is(value, arguments[1])) return value;
return resolveException(value, "%v is not an iterable value", arguments[1]);
};
24 changes: 24 additions & 0 deletions test/iterable/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use strict";

var assert = require("chai").assert
, ensureIterable = require("../../iterable/ensure");

describe("iterable/ensure", function () {
it("Should return input value", function () {
var value = [];
assert.equal(ensureIterable(value), value);
});
it("Should allow strings with allowString option", function () {
var value = "foo";
assert.equal(ensureIterable(value, { allowString: true }), value);
});
it("Should crash on invalid value", function () {
try {
ensureIterable("foo");
throw new Error("Unexpected");
} catch (error) {
assert.equal(error.name, "TypeError");
assert(error.message.includes("is not an iterable value"));
}
});
});

0 comments on commit 3d48841

Please sign in to comment.