Skip to content

Instantly share code, notes, and snippets.

@seanspradlin
Last active May 5, 2016 19:08
Show Gist options
  • Save seanspradlin/7578c53052f9a8c125eef2c4e4e704eb to your computer and use it in GitHub Desktop.
Save seanspradlin/7578c53052f9a8c125eef2c4e4e704eb to your computer and use it in GitHub Desktop.
A slightly involved example for students to learn how closure works
'use strict';
const WeightGoals = {
QUICK_LOSS: 1,
GRADUAL_LOSS: 2,
MAINTENANCE: 3,
BULK: 4,
};
const Gender = {
MALE: 1,
FEMALE: 2,
};
function calorieCounter(gender, weightGoal) {
let caloricBase;
switch (gender) {
case Gender.MALE:
caloricBase = 2100;
break;
case Gender.FEMALE:
caloricBase = 1800;
break;
default:
throw new RangeError('gender must be male or female');
}
switch (weightGoal) {
case WeightGoals.QUICK_LOSS:
caloricBase -= 600;
break;
case WeightGoals.GRADUAL_LOSS:
caloricBase -= 300;
break;
case WeightGoals.MAINTENANCE:
break;
case WeightGoals.BULK:
caloricBase += 600;
break;
default:
throw new RangeError('Invalid weight goal');
}
function addMeal(calories) {
console.log(`Consumed ${calories} calories.`);
caloricBase -= calories;
}
function addExercise(calories) {
console.log(`Burned ${calories} calories.`);
caloricBase += calories;
}
function caloriesRemaining() {
console.log(`${caloricBase} calories remaining`);
}
return {
addMeal,
addExercise,
caloriesRemaining,
};
}
// Execution
// Notice that the caloricBase value will be remembered by the counter1 object
const counter1 = calorieCounter(Gender.MALE, WeightGoals.BULK);
counter1.addMeal(500);
counter1.addMeal(300);
counter1.addExercise(250);
counter1.caloriesRemaining();
// We can create a second instance of the counter and track a completely different caloricBase value
const counter2 = calorieCounter(Gender.FEMALE, WeightGoals.GRADUAL_LOSS);
counter2.addMeal(150);
counter2.addExercise(200);
counter2.addMeal(600);
counter2.caloriesRemaining();
// The original counter remains unchanged
counter1.caloriesRemaining();
console.log(counter1.caloricBase); // undefined: caloricBase is hidden to external scope
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment