Skip to content

Commit

Permalink
feat: reg-exp/ensure
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Apr 3, 2019
1 parent 9728519 commit 6f7bbcb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,17 @@ isRegExp({}); // false
isRegExp("foo"); // false
```

##### `reg-exp/ensure`

If given argument is a regular expression object, it is returned back. Otherwise `TypeError` is thrown.

```javascript
const ensureRegExp = require("type/reg-exp/ensure");

ensureRegExp(/foo/); // /foo/
ensureRegExp("foo"); // Thrown TypeError: null is not a regular expression object
```

### Tests

$ npm test
Expand Down
9 changes: 9 additions & 0 deletions reg-exp/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)) return value;
return resolveException(value, "%v is not a regular expression object", arguments[1]);
};
20 changes: 20 additions & 0 deletions test/reg-exp/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"use strict";

var assert = require("chai").assert
, ensureRegExp = require("../../reg-exp/ensure");

describe("reg-exp/ensure", function () {
it("Should return input value", function () {
var value = /foo/;
assert.equal(ensureRegExp(value), value);
});
it("Should crash on invalid value", function () {
try {
ensureRegExp(null);
throw new Error("Unexpected");
} catch (error) {
assert.equal(error.name, "TypeError");
assert(error.message.includes("is not a regular expression object"));
}
});
});

0 comments on commit 6f7bbcb

Please sign in to comment.