Skip to content

Commit 74716d3

Browse files
committed
stream: truncate fractional limits in take() and drop()
toIntegerOrInfinity() coerced the limit with Number() but never truncated it, so a fractional limit such as 1.5 made take() yield one chunk too many and drop() skip one chunk too many. A negative fraction in (-1, 0) also threw ERR_OUT_OF_RANGE, although ToIntegerOrInfinity() maps it to -0, which is a valid limit. Truncate the value toward zero before the range check so the results match Iterator.prototype.take() and Iterator.prototype.drop(). Signed-off-by: koreahghg <koreahghg@gmail.com> Assisted-by: Claude Code
1 parent 678c555 commit 74716d3

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

‎lib/internal/streams/operators.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const {
44
ArrayPrototypePush,
55
Boolean,
66
MathFloor,
7+
MathTrunc,
78
Number,
89
NumberIsNaN,
910
Promise,
@@ -314,10 +315,11 @@ function toIntegerOrInfinity(number) {
314315
if (NumberIsNaN(number)) {
315316
return 0;
316317
}
317-
if (number < 0) {
318+
const integer = MathTrunc(number);
319+
if (integer < 0) {
318320
throw new ERR_OUT_OF_RANGE('number', '>= 0', number);
319321
}
320-
return number;
322+
return integer;
321323
}
322324

323325
function drop(number, options = undefined) {

‎test/parallel/test-stream-drop-take.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ const naturals = () => from(async function*() {
8181
})().then(common.mustCall());
8282
}
8383

84+
{
85+
// Fractional limits are truncated toward zero
86+
(async () => {
87+
assert.deepStrictEqual(await from([1, 2, 3, 4]).take(1.5).toArray(), [1]);
88+
assert.deepStrictEqual(await from([1, 2, 3, 4]).drop(1.5).toArray(), [2, 3, 4]);
89+
assert.deepStrictEqual(await from([1, 2, 3, 4]).take(0.5).toArray(), []);
90+
assert.deepStrictEqual(await from([1, 2, 3, 4]).drop(0.5).toArray(), [1, 2, 3, 4]);
91+
assert.deepStrictEqual(await from([1, 2]).take(-0.5).toArray(), []);
92+
assert.deepStrictEqual(await from([1, 2]).drop(-0.5).toArray(), [1, 2]);
93+
})().then(common.mustCall());
94+
}
95+
8496
{
8597
// Support for AbortSignal
8698
const ac = new AbortController();
@@ -108,6 +120,7 @@ const naturals = () => from(async function*() {
108120
// Error cases
109121
const invalidArgs = [
110122
-1,
123+
-1.5,
111124
-Infinity,
112125
-40,
113126
];

0 commit comments

Comments
 (0)