From 4fb2614419bbe49963b9ed5cb0aceeb188334439 Mon Sep 17 00:00:00 2001 From: Maxim Devoir Date: Wed, 13 Nov 2019 00:09:02 -0800 Subject: [PATCH] Gracefully handle non-string inputs (#9) --- index.d.ts | 3 ++- index.js | 2 +- index.test-d.ts | 5 +++++ readme.md | 4 ++-- test.js | 10 ++++++++++ 5 files changed, 20 insertions(+), 4 deletions(-) diff --git a/index.d.ts b/index.d.ts index 76a858b..1f32fd2 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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; diff --git a/index.js b/index.js index 919598d..987ed87 100644 --- a/index.js +++ b/index.js @@ -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'; diff --git a/index.test-d.ts b/index.test-d.ts index 9593f0f..13c7047 100644 --- a/index.test-d.ts +++ b/index.test-d.ts @@ -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'])); diff --git a/readme.md b/readme.md index f1a1b9a..eee16c2 100644 --- a/readme.md +++ b/readme.md @@ -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 diff --git a/test.js b/test.js index 8d0b183..15b4796 100644 --- a/test.js +++ b/test.js @@ -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'); });