Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle non-string inputs #9

Merged
merged 10 commits into from Nov 13, 2019
5 changes: 4 additions & 1 deletion index.d.ts
@@ -1,3 +1,5 @@
type IsString<T> = T extends string ? T : never;

declare const detectNewline: {
/**
Detect the dominant newline character of a string.
Expand All @@ -19,7 +21,8 @@ declare const detectNewline: {

@returns Returns detected newline or `\n` when no newline character is found.
*/
graceful(string: string): '\r\n' | '\n';
graceful<T>(string: T & IsString<T>): '\r\n' | '\n';
MaximDevoir marked this conversation as resolved.
Show resolved Hide resolved
graceful(string?: any): '\n';
MaximDevoir marked this conversation as resolved.
Show resolved Hide resolved
};

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']));
2 changes: 1 addition & 1 deletion readme.md
Expand Up @@ -26,7 +26,7 @@ detectNewline('foo\nbar\nbaz\r\n');

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

### detectNewline.graceful(string)
### detectNewline.graceful(any)

Returns the detected newline or `\n` when no newline character is found.
MaximDevoir marked this conversation as resolved.
Show resolved Hide resolved

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');
});