Skip to content

Commit

Permalink
feat: string/ensure
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Mar 25, 2019
1 parent f0a26a3 commit b62577d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ stringCoerce(12); // "12"
stringCoerce(undefined); // null
```

##### `string/ensure`

If given argument is a string coercible value, returns string representation.
Otherwise `TypeError` is thrown.

```javascript
const ensureString = require("type/string/ensure");

ensureString(12); // "12"
ensureString(null); // Thrown TypeError: null is not a string
```

#### Value

_Value_ is assumed to be any JavaScript value that's neither `null` nor `undefined` (_the only primitives which are not accompanied with object representation. Hence any property access on them (as e.g. `null.foo`) results with an exception_)
Expand Down
10 changes: 10 additions & 0 deletions string/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"use strict";

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

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

var assert = require("chai").assert
, ensureString = require("../../string/ensure");

describe("string/ensure", function () {
it("Should return coerced value", function () { assert.equal(ensureString(12), "12"); });
it("Should crash on no value", function () {
try {
ensureString(null);
throw new Error("Unexpected");
} catch (error) {
assert.equal(error.name, "TypeError");
assert.equal(error.message, "null is not a string");
}
});
});

0 comments on commit b62577d

Please sign in to comment.