Skip to content

Instantly share code, notes, and snippets.

@misterussell
Created June 13, 2017 15:17
Show Gist options
  • Save misterussell/7478908ff5fbc93b4bfd7f8b40428953 to your computer and use it in GitHub Desktop.
Save misterussell/7478908ff5fbc93b4bfd7f8b40428953 to your computer and use it in GitHub Desktop.
Practice exercise in moving away from for loops while minimizing side effects.
const waffles = [
{ name: 'Chocolate Chip', calories: 800 },
{ name: 'Blueberry', calories: 400 },
{ name: 'Whole Grain', calories: 350 },
{ name: 'Savory', calories: 600 }
];
const isHealthy = waffle => waffle.calories < 200;
const getName = waffle => waffle.name;
const getItemNames = items => items.filter(isHealthy).map(getName);
// A promise is being used just for continued practice
let verifyBreakfastOptions = new Promise(function(resolve, reject) {
// verify the options based on the cal value above
let healthyBreakfasts = getItemNames(waffles);
// if an array is returned with something in it, the promise resolves, otherwise it is rejected with a message in the catch
if (healthyBreakfasts.length) {
resolve(healthyBreakfasts);
} else {
healthyBreakfasts = null;
reject(healthyBreakfasts);
}
});
verifyBreakfastOptions
.then((output) => {
// non-mutative definition that will interpret the data and convert it to a text string.
let options = output.toString().replace(',', ' and ');
console.log("You can eat the following:", options + '.');
})
.catch((output) => {
console.log("No items were found.");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment