Skip to content

Instantly share code, notes, and snippets.

@jsullivan5
Last active August 12, 2017 18:43
Show Gist options
  • Save jsullivan5/6e590142516cc069eb618daea3732ae8 to your computer and use it in GitHub Desktop.
Save jsullivan5/6e590142516cc069eb618daea3732ae8 to your computer and use it in GitHub Desktop.

Mod 4 Promises Homework

James Sullivan

The goal of this assignment is to familiarize ourselves with promises by writing functions that can (and should) be written without them. The functions below each take in an array and returns a promise. makeAllCaps() capitolizes each element in an array and rejects if an element is not a string. sortWords() sorts the elements alphabetically and also rejects if an element is not a string.

const array = ['wowow', 'pants', 'bird'];
const array2 = ['wowow', 5, 'bird'];

const makeAllCaps = (array) => {
  return new Promise( (resolve, reject) => {
    if (array.find(e => typeof e !== 'string') === undefined) {
      resolve(array.map(word => word.toUpperCase()))
    } else {
      reject('No, the array you passed in contained an element that was not a string!')
    }
  });
}

const sortWords = (array) => {
  return new Promise( (resolve, reject) => {
    if (array.find(e => typeof e !== 'string') === undefined) {
      resolve(array.sort())
    } else {
      reject('No, the array you passed in contained an element that was not a string!')
    }
  });
}

makeAllCaps(array)
  .then(sortWords)
  .then((result) => console.log(result))
  .catch(error => console.log(error));
  
// [ 'BIRD', 'PANTS', 'WOWOW' ]
  
makeAllCaps(array2)
  .then(sortWords)
  .then((result) => console.log(result))
  .catch(error => console.log(error));
  
// No, the array you passed in contained an element that was not a string!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment