Skip to content

Commit

Permalink
Gracefully handle non-string inputs (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
MaximDevoir authored and sindresorhus committed Nov 13, 2019
1 parent ecf81a3 commit 4fb2614
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 4 deletions.
3 changes: 2 additions & 1 deletion index.d.ts
Expand Up @@ -17,9 +17,10 @@ declare const detectNewline: {
/**
Detect the dominant newline character of a string.
@returns Returns detected newline or `\n` when no newline character is found.
@returns The detected newline or `\n` when no newline character is found or the input is not a string.
*/
graceful(string: string): '\r\n' | '\n';
graceful(string?: unknown): '\n';
};

export = detectNewline;
2 changes: 1 addition & 1 deletion index.js
Expand Up @@ -18,4 +18,4 @@ const detectNewline = string => {
};

module.exports = detectNewline;
module.exports.graceful = string => detectNewline(string) || '\n';
module.exports.graceful = string => (typeof string === 'string' && detectNewline(string)) || '\n';
5 changes: 5 additions & 0 deletions index.test-d.ts
Expand Up @@ -3,3 +3,8 @@ import detectNewline = require('.');

expectType<'\r\n' | '\n' | undefined>(detectNewline('foo\nbar\nbaz\r\n'));
expectType<'\r\n' | '\n'>(detectNewline.graceful('foo\nbar\nbaz\r\n'));
expectType<'\n'>(detectNewline.graceful(null));
expectType<'\n'>(detectNewline.graceful(undefined));
expectType<'\n'>(detectNewline.graceful());
expectType<'\n'>(detectNewline.graceful(1));
expectType<'\n'>(detectNewline.graceful(['foo', 'bar']));
4 changes: 2 additions & 2 deletions readme.md
Expand Up @@ -26,9 +26,9 @@ detectNewline('foo\nbar\nbaz\r\n');

Returns the detected newline or `undefined` when no newline character is found.

### detectNewline.graceful(string)
### detectNewline.graceful(unknown)

Returns the detected newline or `\n` when no newline character is found.
Returns the detected newline or `\n` when no newline character is found or the input is not a string.


## Related
Expand Down
10 changes: 10 additions & 0 deletions test.js
Expand Up @@ -7,5 +7,15 @@ test('main', t => {
t.is(detectNewline('foo\nbar\nbaz\r\n'), '\n');
t.is(detectNewline('foo\nbar\r\n'), '\n');
t.is(detectNewline('foo'), undefined);
});

test('graceful', t => {
t.is(detectNewline.graceful('foo'), '\n');
t.is(detectNewline.graceful('foo\r\nbar\r\nbaz\n'), '\r\n');
t.is(detectNewline.graceful(null), '\n');
t.is(detectNewline.graceful(undefined), '\n');
t.is(detectNewline.graceful(), '\n');
t.is(detectNewline.graceful(0), '\n');
t.is(detectNewline.graceful(true), '\n');
t.is(detectNewline.graceful(['foo', 'bar']), '\n');
});

0 comments on commit 4fb2614

Please sign in to comment.