Skip to content

Commit

Permalink
Return undefined instead of null when no newline is found
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Apr 11, 2019
1 parent 841de59 commit 446e98c
Show file tree
Hide file tree
Showing 5 changed files with 10 additions and 9 deletions.
4 changes: 2 additions & 2 deletions index.d.ts
Expand Up @@ -2,7 +2,7 @@ declare const detectNewline: {
/**
Detect the dominant newline character of a string.
@returns Detected newline or `null` when no newline character is found.
@returns The detected newline or `undefined` when no newline character is found.
@example
```
Expand All @@ -12,7 +12,7 @@ declare const detectNewline: {
//=> '\n'
```
*/
(string: string): '\r\n' | '\n' | null;
(string: string): '\r\n' | '\n' | undefined;

/**
Detect the dominant newline character of a string.
Expand Down
5 changes: 3 additions & 2 deletions index.js
@@ -1,4 +1,5 @@
'use strict';

const detectNewline = string => {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
Expand All @@ -7,10 +8,10 @@ const detectNewline = string => {
const newlines = string.match(/(?:\r?\n)/g) || [];

if (newlines.length === 0) {
return null;
return;
}

const crlf = newlines.filter(el => el === '\r\n').length;
const crlf = newlines.filter(newline => newline === '\r\n').length;
const lf = newlines.length - crlf;

return crlf > lf ? '\r\n' : '\n';
Expand Down
2 changes: 1 addition & 1 deletion index.test-d.ts
@@ -1,5 +1,5 @@
import {expectType} from 'tsd';
import detectNewline = require('.');

expectType<'\r\n' | '\n' | null>(detectNewline('foo\nbar\nbaz\r\n'));
expectType<'\r\n' | '\n' | undefined>(detectNewline('foo\nbar\nbaz\r\n'));
expectType<'\r\n' | '\n'>(detectNewline.graceful('foo\nbar\nbaz\r\n'));
6 changes: 3 additions & 3 deletions readme.md
Expand Up @@ -24,11 +24,11 @@ detectNewline('foo\nbar\nbaz\r\n');

### detectNewline(string)

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

### detectNewline.graceful(string)

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


## Related
Expand All @@ -39,4 +39,4 @@ Returns detected newline or `\n` when no newline character is found.

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)
MIT © [Sindre Sorhus](https://sindresorhus.com)
2 changes: 1 addition & 1 deletion test.js
Expand Up @@ -6,6 +6,6 @@ test('main', t => {
t.is(detectNewline('foo\r\nbar\r\nbaz\n'), '\r\n');
t.is(detectNewline('foo\nbar\nbaz\r\n'), '\n');
t.is(detectNewline('foo\nbar\r\n'), '\n');
t.is(detectNewline('foo'), null);
t.is(detectNewline('foo'), undefined);
t.is(detectNewline.graceful('foo'), '\n');
});

0 comments on commit 446e98c

Please sign in to comment.