Skip to content

Instantly share code, notes, and snippets.

@ryunp
Last active February 19, 2020 01:19
Show Gist options
  • Save ryunp/e1d8a18146e5cef69c3479782a65f332 to your computer and use it in GitHub Desktop.
Save ryunp/e1d8a18146e5cef69c3479782a65f332 to your computer and use it in GitHub Desktop.
/*
Author: Ryan Paul
Date: 12/03/18
Description: Extracted code showing iterations over basic file existence functionality
Environment: Node.js
*/
// Iteation 1: Initial attempt:
function isInstalled(installPath) {
const fileNames = ['Game.exe', 'Diablo II.exe', 'd2data.mpq']
const files = fileNames.map(file => path.join(installPath, file))
const promises = files.map(file => accessAsync(file))
return Promise.all(promises).then(assertAllTrue)
function assertAllTrue(results) {
return results.every(result => result === true)
}
}
// Iteation 2: Async syntax version:
async function isInstalled(installPath) {
const fileNames = ['Game.exe', 'Diablo II.exe', 'd2data.mpq']
const files = fileNames.map(file => path.join(installPath, file))
const promises = files.map(file => accessAsync(file))
const results = await Promise.all(promises)
return results.every(result => result === true)
}
// Iteation 3: Fully inlined:
function isInstalled(installPath) {
return Promise.all(
['Game.exe', 'Diablo II.exe', 'd2data.mpq']
.map(file => accessAsync(path.join(installPath, file)))
).then(results => results.every(result => result === true))
}
// Iteration 4: Extract promise.all behavior into accessAsyncAll():
// (Not much gained from this, meh)
function isInstalled(installPath) {
const files = ['Game.exe', 'Diablo II.exe', 'd2data.mpq']
.map(file => path.join(installPath, file))
return accessAllAsync(files).then(assertAllTrue)
function assertAllTrue(array) {
return array.every(value => value === true)
}
}
// Conclusion: Combine iterations into most readable version:
async function isInstalled(installPath) {
const promises = ['Game.exe', 'Diablo II.exe', 'd2data.mpq']
.map(file => accessAsync(path.join(installPath, file)))
const results = await Promise.all(promises)
return results.every(value => value === true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment