Skip to content

Commit

Permalink
feat: function/ensure
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Apr 4, 2019
1 parent dab8026 commit b624c9a
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,18 @@ isFunction(class {}); // true
isFunction("foo"); // false
```

#### `function/ensure`

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

```javascript
const ensureFunction = require("type/function/ensure");

const fn = function () {};
ensureDate(fn); // fn
ensureDate(/foo/); // Thrown TypeError: /foo/ is not a function
```

---

### RegExp
Expand Down
9 changes: 9 additions & 0 deletions function/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 function", arguments[1]);
};
20 changes: 20 additions & 0 deletions test/function/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"use strict";

var assert = require("chai").assert
, ensureFunction = require("../../function/ensure");

describe("function/ensure", function () {
it("Should return input value", function () {
var value = function () { return true; };
assert.equal(ensureFunction(value), value);
});
it("Should crash on invalid value", function () {
try {
ensureFunction(null);
throw new Error("Unexpected");
} catch (error) {
assert.equal(error.name, "TypeError");
assert(error.message.includes("is not a function"));
}
});
});

0 comments on commit b624c9a

Please sign in to comment.