Skip to content

Commit c9564b5

Browse files
committed
improve: Now returning "0s" for 0 ms or invalid input
Signed-off-by: Jaid <jaid.jsx@gmail.com>
1 parent 5d8f7ee commit c9564b5

File tree

2 files changed

+24
-13
lines changed

2 files changed

+24
-13
lines changed

src/index.js

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,7 @@
22

33
import humanizeDuration from "humanize-duration"
44

5-
/**
6-
* @function
7-
* @param {number} milliseconds
8-
* @returns {string} Formatted duration
9-
* @example
10-
* import readableMs from "readable-ms"
11-
* const result = readableMs(3021)
12-
* result === "3s 21ms"
13-
*/
14-
export default humanizeDuration.humanizer({
5+
const humanizer = humanizeDuration.humanizer({
156
units: ["h", "m", "s", "ms"],
167
spacer: "",
178
delimiter: " ",
@@ -24,4 +15,23 @@ export default humanizeDuration.humanizer({
2415
ms: () => "ms",
2516
},
2617
},
27-
})
18+
})
19+
20+
/**
21+
* @function
22+
* @param {number} milliseconds
23+
* @returns {string} Formatted duration
24+
* @example
25+
* import readableMs from "readable-ms"
26+
* const result = readableMs(3021)
27+
* result === "3s 21ms"
28+
* const result2 = readableMs(0)
29+
* result2 === "0s"
30+
*/
31+
export default ms => {
32+
if (Number.isFinite(ms) && ms !== 0) {
33+
return humanizer(ms)
34+
} else {
35+
return "0s"
36+
}
37+
}

test/test.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const indexModule = (process.env.MAIN ? path.resolve(process.env.MAIN) : path.jo
88
const {default: readableMs} = indexModule
99

1010
it("should run", () => {
11-
const result = readableMs(3021)
12-
expect(result).toBe("3s 21ms")
11+
expect(readableMs(3021)).toBe("3s 21ms")
12+
expect(readableMs(0)).toBe("0s")
13+
expect(readableMs()).toBe("0s")
1314
})

0 commit comments

Comments
 (0)