Skip to content

Commit

Permalink
feat: string/coerce
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Mar 25, 2019
1 parent d2d7251 commit b25c71f
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ isObject(true); // false
isObject(null); // false
```

#### String

_string_ primitives

##### `string/coerce`

Restricted string coercion. Returns `null` for non-values or non implicitly coercible (to string) values

```javascript
const stringCoerce = require("type/string/coerce");

stringCoerce(12); // "12"
stringCoerce(undefined); // null
```

#### 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
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@
"files": "test/**/*.js",
"env": {
"mocha": true
},
"rules": {
"no-new-wrappers": "off"
}
},
{
"files": "string/coerce.js",
"rules": {
"no-implicit-coercion": "off"
}
}
]
Expand Down
12 changes: 12 additions & 0 deletions string/coerce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"use strict";

var isValue = require("../value/is");

module.exports = function (value) {
if (!isValue(value)) return null;
try {
return "" + value; // Ensureimplicit coercion
} catch (error) {
return null;
}
};
27 changes: 27 additions & 0 deletions test/string/coerce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"use strict";

var assert = require("chai").assert
, stringCoerce = require("../../string/coerce");

describe("string/coerce", function () {
it("Should return input string", function () { assert.equal(stringCoerce("foo"), "foo"); });
it("Should coerce numbers", function () { assert.equal(stringCoerce(12), "12"); });
it("Should coerce booleans", function () { assert.equal(stringCoerce(true), "true"); });
it("Should coerce string objects", function () {
assert.equal(stringCoerce(new String("bar")), "bar");
});
it("Should coerce objects", function () {
assert.equal(
stringCoerce({ toString: function () { return "Some object"; } }), "Some object"
);
});
it("Should not coerce null", function () { assert.equal(stringCoerce(null), null); });
it("Should not coerce undefined", function () { assert.equal(stringCoerce(undefined), null); });

if (typeof Symbol === "function") {
it("Should not coerce symbols", function () {
// eslint-disable-next-line no-undef
assert.equal(stringCoerce(Symbol()), null);
});
}
});

0 comments on commit b25c71f

Please sign in to comment.