Skip to content

feat: .pmap method for promisify .map #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,50 @@ map(['a', 'b', 'c'], function (ele, i) {
//=> ['0a', '1b', '2c']
```

### [.pmap](lib/array/pmap.js#L27)

This will queue async/await operation on JavaScript's native array map to resolve after the queue is empty, instead of using Promise.all() that will run function on element in parallel and wait until all individually resolve

**Params**

* `array` **{Array}**
* `fn` **{Promise<Function>}**
* `returns` **{Promise<Array>}**

**Example**

```js
async function fn (each) {
each + each
}

await ['a', 'b', 'c'].map(async function (each) {
return await fn(each)
});
//=> ['aa', 'bb', 'cc']

await map(['a', 'b', 'c'], async function (each) {
return await fn(each)
});
//=> ['aa', 'bb', 'cc']

map(['a', 'b', 'c'], function (each, i) {
return new Promise( function( resolve ){
resolve( i + each )
})
})
.then( console.log )
//=> ['0a', '1b', '2c']

['a', 'b', 'c'].map(function (each, i) {
return new Promise( function (resolve) {
resolve( i + each )
})
})
.then( console.log )
//=> ['0a', '1b', '2c']
```

### [.slice](lib/array/slice.js#L21)

Alternative to JavaScript's native array-slice method. Slices `array` from the `start` index up to but not including the `end` index.
Expand Down
73 changes: 73 additions & 0 deletions lib/array/pmap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
'use strict';

/**
* Returns a new array with the results of calling promise function
* on every element in the array.
*
* This will queue async/await operation on JavaScript's native array
* map to resolve after the queue is empty, instead of using Promise.all()
* that will run function on element in parallele and wait until all
* individually resolve
*
* ```js
* async function fn( each ){
* each + each
* }
*
* await ['a', 'b', 'c'].map(async function (each) {
* return await fn( each )
* });
* //=> ['aa', 'bb', 'cc']
*
* await map(['a', 'b', 'c'], async function (each) {
* return await fn( each )
* });
* //=> ['aa', 'bb', 'cc']
*
* map(['a', 'b', 'c'], function (each, i) {
* return new Promise( function( resolve ){
* resolve( i + each )
* })
* })
* .then( console.log )
* //=> ['0a', '1b', '2c']
*
* ['a', 'b', 'c'].map(function (each, i) {
* return new Promise( function( resolve ){
* resolve( i + each )
* })
* })
* .then( console.log )
* //=> ['0a', '1b', '2c']
* ```
*
* @name .pmap
* @param {Array} `input`
* @param {Promise<Function>} `fn`
* @return {Promise<Array>}
* @api public
*/
async function operator( input, fn ){
if( !Array.isArray( input ) || !input.length )
return []

let counter = 0
const
_array = JSON.parse( JSON.stringify( input ) ),
output = [],
recursor = async function(){
const each = _array.shift()
output.push( await fn( each, counter++ ) || each )

// Recursive async/await
if( _array.length ) await recursor()
}

await recursor()
return output
}

// Add direct prototype to native array
Array.prototype.pmap = async function( fn ){ return operator( this, fn ) }

module.exports = function( array, fn ){ return operator( array, fn ) }
30 changes: 30 additions & 0 deletions test/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,36 @@ describe('array utils:', function() {
});
});

describe('pmap', function() {
it('should return an empty array when undefined.', async function() {
await utils.map().should.eql([]);
});

it('should map the items in the array and return new values.', async function() {
async function fn( str ){
return str + str
}

const result = await utils.pmap(['a','b','c'], async function(str) {
return await fn( str )
})

result.should.eql(['aa', 'bb', 'cc'])
});

it('should map the items in the array and return new values (Prototype).', async function() {
async function fn( str, i ){
return i + str
}

const result = await ['a','b','c'].pmap( async function(str, i) {
return await fn( str, i )
})

result.should.eql(['0a', '1b', '2c'])
});
});

describe('sort', function() {
it('should throw on bad args.', function() {
(function () {
Expand Down
Loading