Skip to content

Commit

Permalink
Resolves #362: replace generator functions with promises
Browse files Browse the repository at this point in the history
  • Loading branch information
webketje committed Feb 20, 2022
1 parent 9d03820 commit 16a91c5
Show file tree
Hide file tree
Showing 2 changed files with 192 additions and 144 deletions.
57 changes: 46 additions & 11 deletions lib/helpers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const fs = require('fs')
const { promisify } = require('util')
const { resolve, relative, normalize } = require('path')
const { resolve, relative, normalize, dirname } = require('path')
const rmrf = require('rimraf')
const micromatch = require('micromatch')

Expand Down Expand Up @@ -67,11 +67,11 @@ function rm(p) {

/**
* Recursive readdir with support for ignores
* @private
* @param {String} dir
* @param {Array<String|Function>} ignores
* @param {Function} callback - Callback for thunkify @TODO remove in the future
*/
function readdir(dir, ignores, callback) {
function readdir(dir, ignores) {
if (Array.isArray(ignores)) {
ignores = {
str: ignores.filter(isString),
Expand Down Expand Up @@ -122,15 +122,47 @@ function readdir(dir, ignores, callback) {
.sort()
return result
})
.catch((err) => {
throw err
})

return result
}

/**
* Run `fn` in parallel on #`concurrency` number of `items`, spread over #`items / concurrency` sequential batches
* @private
* @param {() => Promise} fn
* @param {*[]} items
* @param {number} concurrency
* @returns {Promise<*[]>}
*/
function batchAsync(fn, items, concurrency) {
let batches = Promise.resolve([])
items = [...items]

if (callback) {
result.then(
(files) => callback(null, files),
(err) => callback(err)
)
} else {
return result
while (items.length) {
const slice = items.splice(0, concurrency)
batches = batches.then((previousBatch) => {
return Promise.all(slice.map((...args) => fn(...args))).then((currentBatch) => [
...previousBatch,
...currentBatch
])
})
}

return batches
}

/**
* Output a file and create any non-existing directories in the process
* @private
**/
function outputFile(file, data, mode) {
const writeFile = promisify(fs.writeFile)
return promisify(fs.mkdir)(dirname(file), { recursive: true }).then(() => {
return writeFile(file, data, mode ? { mode } : undefined)
})
}

const helpers = {
Expand All @@ -139,9 +171,12 @@ const helpers = {
isString,
isObject,
isUndefined,
isFunction,
match,
rm,
readdir
readdir,
outputFile,
batchAsync
}

module.exports = helpers
Loading

0 comments on commit 16a91c5

Please sign in to comment.