Skip to content

Commit

Permalink
Require Node.js 12 and move to ESM
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Apr 8, 2021
1 parent 36ccc22 commit d36cb78
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 121 deletions.
4 changes: 1 addition & 3 deletions .github/workflows/main.yml
Expand Up @@ -12,11 +12,9 @@ jobs:
node-version:
- 14
- 12
- 10
- 8
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm install
Expand Down
97 changes: 40 additions & 57 deletions index.d.ts
@@ -1,57 +1,40 @@
declare namespace pReduce {
type ReducerFunction<ValueType, ReducedValueType = ValueType> = (
previousValue: ReducedValueType,
currentValue: ValueType,
index: number
) => PromiseLike<ReducedValueType> | ReducedValueType;
}

declare const pReduce: {
/**
Reduce a list of values using promises into a promise for a value.
@param input - Iterated over serially in the `reducer` function.
@param reducer - Expected to return a value. If a `Promise` is returned, it's awaited before continuing with the next iteration.
@param initialValue - Value to use as `previousValue` in the first `reducer` invocation.
@returns A `Promise` that is fulfilled when all promises in `input` and ones returned from `reducer` are fulfilled, or rejects if any of the promises reject. The resolved value is the result of the reduction.
@example
```
import pReduce = require('p-reduce');
import humanInfo from 'human-info'; // Not a real module
(async () => {
const names = [
getUser('sindresorhus').then(info => info.name),
'Addy Osmani',
'Pascal Hartig',
'Stephen Sawchuk'
];
const totalAge = await pReduce(names, async (total, name) => {
const info = await humanInfo(name);
return total + info.age;
}, 0);
console.log(totalAge);
//=> 125
})();
```
*/
<ValueType, ReducedValueType = ValueType>(
input: Iterable<PromiseLike<ValueType> | ValueType>,
reducer: pReduce.ReducerFunction<ValueType, ReducedValueType>,
initialValue?: ReducedValueType
): Promise<ReducedValueType>;

// TODO: Remove this for the next major release, refactor the whole definition to:
// declare function pReduce<ValueType, ReducedValueType = ValueType>(
// input: Iterable<PromiseLike<ValueType> | ValueType>,
// reducer: pReduce.ReducerFunction<ValueType, ReducedValueType>,
// initialValue?: ReducedValueType
// ): Promise<ReducedValueType>;
// export = pReduce;
default: typeof pReduce;
};

export = pReduce;
export type ReducerFunction<ValueType, ReducedValueType = ValueType> = (
previousValue: ReducedValueType,
currentValue: ValueType,
index: number
) => PromiseLike<ReducedValueType> | ReducedValueType;

/**
Reduce a list of values using promises into a promise for a value.
@param input - Iterated over serially in the `reducer` function.
@param reducer - Expected to return a value. If a `Promise` is returned, it's awaited before continuing with the next iteration.
@param initialValue - Value to use as `previousValue` in the first `reducer` invocation.
@returns A `Promise` that is fulfilled when all promises in `input` and ones returned from `reducer` are fulfilled, or rejects if any of the promises reject. The resolved value is the result of the reduction.
@example
```
import pReduce from 'p-reduce';
import humanInfo from 'human-info'; // Not a real module
const names = [
getUser('sindresorhus').then(info => info.name),
'Addy Osmani',
'Pascal Hartig',
'Stephen Sawchuk'
];
const totalAge = await pReduce(names, async (total, name) => {
const info = await humanInfo(name);
return total + info.age;
}, 0);
console.log(totalAge);
//=> 125
```
*/
export default function pReduce<ValueType, ReducedValueType = ValueType>(
input: Iterable<PromiseLike<ValueType> | ValueType>,
reducer: ReducerFunction<ValueType, ReducedValueType>,
initialValue?: ReducedValueType
): Promise<ReducedValueType>;
44 changes: 20 additions & 24 deletions index.js
@@ -1,28 +1,24 @@
'use strict';
export default async function pReduce(iterable, reducer, initialValue) {
return new Promise((resolve, reject) => {
const iterator = iterable[Symbol.iterator]();
let index = 0;

const pReduce = (iterable, reducer, initialValue) => new Promise((resolve, reject) => {
const iterator = iterable[Symbol.iterator]();
let index = 0;
const next = async total => {
const element = iterator.next();

const next = async total => {
const element = iterator.next();
if (element.done) {
resolve(total);
return;
}

if (element.done) {
resolve(total);
return;
}
try {
const [resolvedTotal, resolvedValue] = await Promise.all([total, element.value]);
next(reducer(resolvedTotal, resolvedValue, index++));
} catch (error) {
reject(error);
}
};

try {
const value = await Promise.all([total, element.value]);
next(reducer(value[0], value[1], index++));
} catch (error) {
reject(error);
}
};

next(initialValue);
});

module.exports = pReduce;
// TODO: Remove this for the next major release
module.exports.default = pReduce;
next(initialValue);
});
}
4 changes: 2 additions & 2 deletions index.test-d.ts
@@ -1,5 +1,5 @@
import {expectType} from 'tsd';
import pReduce = require('.');
import pReduce from './index.js';

const names = [
Promise.resolve('sindresorhus'),
Expand Down Expand Up @@ -31,7 +31,7 @@ const names2 = [
expectType<Promise<string>>(
pReduce<string | number, string>(
names2,
(allNames, name) => {
async (allNames, name) => {
expectType<string>(allNames);
expectType<string | number>(name);
return Promise.resolve(`${allNames},${name}`);
Expand Down
2 changes: 1 addition & 1 deletion license
@@ -1,6 +1,6 @@
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Expand Down
15 changes: 9 additions & 6 deletions package.json
Expand Up @@ -4,13 +4,16 @@
"description": "Reduce a list of values using promises into a promise for a value",
"license": "MIT",
"repository": "sindresorhus/p-reduce",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=8"
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
Expand All @@ -32,9 +35,9 @@
"bluebird"
],
"devDependencies": {
"ava": "^1.4.1",
"delay": "^4.1.0",
"tsd": "^0.7.2",
"xo": "^0.24.0"
"ava": "^3.15.0",
"delay": "^5.0.0",
"tsd": "^0.14.0",
"xo": "^0.38.2"
}
}
41 changes: 17 additions & 24 deletions readme.md
Expand Up @@ -4,39 +4,34 @@
Useful when you need to calculate some accumulated value based on async resources.


## Install

```
$ npm install p-reduce
```


## Usage

```js
const pReduce = require('p-reduce');
const humanInfo = require('human-info'); // Not a real module

(async () => {
const names = [
getUser('sindresorhus').then(info => info.name),
'Addy Osmani',
'Pascal Hartig',
'Stephen Sawchuk'
];

const totalAge = await pReduce(names, async (total, name) => {
const info = await humanInfo(name);
return total + info.age;
}, 0);

console.log(totalAge);
//=> 125
})();
import pReduce from 'p-reduce';
import humanInfo from 'human-info'; // Not a real module

const names = [
getUser('sindresorhus').then(info => info.name),
'Addy Osmani',
'Pascal Hartig',
'Stephen Sawchuk'
];

const totalAge = await pReduce(names, async (total, name) => {
const info = await humanInfo(name);
return total + info.age;
}, 0);

console.log(totalAge);
//=> 125
```


## API

### pReduce(input, reducer, initialValue?)
Expand All @@ -61,15 +56,13 @@ Type: `unknown`

Value to use as `previousValue` in the first `reducer` invocation.


## Related

- [p-each-series](https://github.com/sindresorhus/p-each-series) - Iterate over promises serially
- [p-map-series](https://github.com/sindresorhus/p-map-series) - Map over promises serially
- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
- [More…](https://github.com/sindresorhus/promise-fun)


---

<div align="center">
Expand Down
8 changes: 4 additions & 4 deletions test.js
@@ -1,6 +1,6 @@
import test from 'ava';
import delay from 'delay';
import pReduce from '.';
import pReduce from './index.js';

test('main', async t => {
const fixture = [
Expand All @@ -18,7 +18,7 @@ test('rejects', async t => {
delay.reject(50, {value: new Error('foo')})
];

await t.throwsAsync(pReduce(fixture, (a, b) => a + b, 0), 'foo');
await t.throwsAsync(pReduce(fixture, (a, b) => a + b, 0), {message: 'foo'});
});

test('reducer throws', async t => {
Expand All @@ -29,9 +29,9 @@ test('reducer throws', async t => {

await t.throwsAsync(pReduce(fixture, () => {
throw new Error('foo');
}), 'foo');
}), {message: 'foo'});
});

test('handles empty iterable', async t => {
t.deepEqual(await pReduce([], () => {}, 0), 0);
t.is(await pReduce([], () => {}, 0), 0);
});

0 comments on commit d36cb78

Please sign in to comment.