Skip to content

Instantly share code, notes, and snippets.

@mstraughan86
Last active January 18, 2018 04:38
Show Gist options
  • Save mstraughan86/f4a0d55bd09a7906cac5223d79bb7636 to your computer and use it in GitHub Desktop.
Save mstraughan86/f4a0d55bd09a7906cac5223d79bb7636 to your computer and use it in GitHub Desktop.
Javascript Utility Belt

Want to handle arguments in vanilla JS? Here is how!

const args = process.argv.slice(2).reduce((accumulator, current) => {
  let [key, value = true] = current.split('=');
  accumulator[key] = value;
  return accumulator;
}, {})

console.log(args);
forever start app.js args
forever logs app.js -f

Want to use vanilla promises, but also want to have some basic control structures? Use this:

const promiseSeries_withCombinedResults = (array, initial, ...args) => {
  const combinedResults = [];
  return array
    .reduce((chain, promise)=>{
      return chain
        .then(result => promise(result, ...args))
        .then(result => {
          combinedResults.push(result);
          Promise.resolve(result);
        })
    }, Promise.resolve(initial))
    .then(()=>Promise.resolve(combinedResults));
};
const promiseSeries = (array, initial, ...args) => {
  return array
    .reduce((chain, promise)=>{
      return chain.then(result => promise(result, ...args));
    }, Promise.resolve(initial));
};
const promiseParallel = (array, ...args) => {
  return Promise.all(array.map(promise=>promise(...args)));
};

const main = (param) => {

  const array = [
    ()=>{
      console.log(1);
      return Promise.resolve(1);
    },
    ()=>{
      console.log(2);
      return Promise.resolve(2);
    },
    ()=>{
      console.log(3);
      return Promise.resolve(3);
    }
  ];

  return promiseSeries_withCombinedResults(array)
    .then(result=>{
      console.log('finished promiseSeries_CombinedResults.', result);
      return Promise.resolve(array);
    })
    .then(promiseSeries)
    .then(result=>{
      console.log('finished promiseSeries.', result);
      return Promise.resolve(array);
    })
    .then(promiseParallel)
    .then(result=>{
      console.log('finished parallel.', result);
    })
    .catch((error)=>{console.log('error:', error)});
};

main()

Read all files in a directory, recursively:

const walk = dir => {
  return fs.readdirSync(dir)
    .reduce((array, file) =>
        fs.statSync(path.join(dir, file)).isDirectory() ?
          array.concat(walk(path.join(dir, file))) :
          array.concat(path.join(dir, file))
      ,[]);
};

Source

Alternatives:

@mstraughan86
Copy link
Author

Check this out for later:
https://stackoverflow.com/questions/36433461/how-do-i-add-a-custom-script-to-my-package-json-file-that-runs-a-javascript-file

Idea:
Make some Life-cycle scripts, a build script, or something so that we can "prep" our system. Make this even more hands off!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment