Skip to content

Instantly share code, notes, and snippets.

@sagarjhaa
Created April 14, 2020 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagarjhaa/7907d2dc51ad3a2c53b2666460f283fb to your computer and use it in GitHub Desktop.
Save sagarjhaa/7907d2dc51ad3a2c53b2666460f283fb to your computer and use it in GitHub Desktop.
Gist on understanding closures - Javascript
// http://csbin.io/closures
// Type JavaScript here and click "Run Code" or press Ctrl + s
console.log('Hello, world!');
// CHALLENGE 1
function createFunction() {
return function(){
console.log('hello');
}
}
// /*** Uncomment these to check your work! ***/
const function1 = createFunction();
function1(); // => should console.log('hello');
// CHALLENGE 2
function createFunctionPrinter(input) {
return function(){
console.log(input);
}
}
// /*** Uncomment these to check your work! ***/
const printSample = createFunctionPrinter('sample');
printSample(); // => should console.log('sample');
const printHello = createFunctionPrinter('hello');
printHello(); // => should console.log('hello');
// CHALLENGE 3
function outer() {
let counter = 0; // this variable is outside incrementCounter's scope
function incrementCounter () {
counter ++;
console.log('counter', counter);
}
return incrementCounter;
}
const willCounter = outer();
const jasCounter = outer();
// Uncomment each of these lines one by one.
// Before your do, guess what will be logged from each function call.
// /*** Uncomment these to check your work! ***/
willCounter(); // 1
willCounter(); // 2
willCounter(); // 3
jasCounter(); // 1
willCounter(); // 4
function addByX(x) {
return function(y){
return x+y;
}
}
// /*** Uncomment these to check your work! ***/
const addByTwo = addByX(2);
addByTwo(1); // => should return 3
addByTwo(2); // => should return 4
addByTwo(3); // => should return 5
const addByThree = addByX(3);
addByThree(1); // => should return 4
addByThree(2); // => should return 5
const addByFour = addByX(4);
addByFour(4); // => should return 8
addByFour(5); // => should return 9
// CHALLENGE 4
function once(func) {
var counter = 0;
var output = 0;
return function(num){
if (counter == 0){
counter++;
output = func(num)
}
return output;
}
}
// /*** Uncomment these to check your work! ***/
const onceFunc = once(addByTwo);
console.log(onceFunc(4)); // => should log 6
console.log(onceFunc(10)); // => should log 6
console.log(onceFunc(9001)); // => should log 6
// CHALLENGE 5
function after(count, func) {
var counter = 1;
return function(){
if (counter >= count){
func()
}
else{
counter++;
}
}
}
// /*** Uncomment these to check your work! ***/
console.log('------------------');
const called = function() { console.log('hello') };
const afterCalled = after(3, called);
afterCalled(); // => nothing is printed
afterCalled(); // => nothing is printed
afterCalled(); // => 'hello' is printed
// CHALLENGE 6
function delay(func, wait) {
setTimeout(func(),wait);
}
// CHALLENGE 7
function rollCall(names) {
var count = 0;
return function (){
if (count < names.length){
console.log(names[count]);
count++
}
else{
console.log("Everyone account for")
}
}
}
// /*** Uncomment these to check your work! ***/
const rollCaller = rollCall(['Victoria', 'Juan', 'Ruth'])
rollCaller() // => should log 'Victoria'
rollCaller() // => should log 'Juan'
rollCaller() // => should log 'Ruth'
rollCaller() // => should log 'Everyone accounted for'
// CHALLENGE 8
function saveOutput(func, magicWord) {
var obj = {};
var output;
return function(arg){
if (arg != magicWord){
output = func(arg);
obj[arg] = output;
return output;
}
else{
return obj;
}
}
}
// /*** Uncomment these to check your work! ***/
const multiplyBy2 = function(num) { return num * 2; };
const multBy2AndLog = saveOutput(multiplyBy2, 'boo');
console.log(multBy2AndLog(2)); // => should log 4
console.log(multBy2AndLog(9)); // => should log 18
console.log(multBy2AndLog('boo')); // => should log { 2: 4, 9: 18 }
// CHALLENGE 9
function cycleIterator(array) {
var count = -1;
return function(){
if (count+1 < array.length){
count++;
return array[count]
}
else{
count = 0;
return array[count];
}
}
}
// /*** Uncomment these to check your work! ***/
const threeDayWeekend = ['Fri', 'Sat', 'Sun'];
const getDay = cycleIterator(threeDayWeekend);
console.log(getDay()); // => should log 'Fri'
console.log(getDay()); // => should log 'Sat'
console.log(getDay()); // => should log 'Sun'
console.log(getDay()); // => should log 'Fri'
// CHALLENGE 10
function defineFirstArg(func, arg) {
return function(second){
return func(arg,second);
}
}
// /*** Uncomment these to check your work! ***/
const subtract = function(big, small) { return big - small; };
const subFrom20 = defineFirstArg(subtract, 20);
console.log(subFrom20(5)); // => should log 15
// CHALLENGE 11
function dateStamp(func) {
return function(){
var today = new Date();
today = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
return {
date: today,
output: func(arguments[0])
}
}
}
// /*** Uncomment these to check your work! ***/
const stampedMultBy2 = dateStamp(n => n * 2);
console.log(stampedMultBy2(4)); // => should log { date: (today's date), output: 8 }
console.log(stampedMultBy2(6)); // => should log { date: (today's date), output: 12 }
// CHALLENGE 12
function censor() {
var d = {}
return function(first,second=null){
if (second != null){
d[first] = second
console.log(d);
}
else{
for(let key in d){
first = first.replace(key,d[key])
}
return first
}
}
}
// /*** Uncomment these to check your work! ***/
const changeScene = censor();
changeScene('dogs', 'cats');
changeScene('quick', 'slow');
console.log(changeScene('The quick, brown fox jumps over the lazy dogs.')); // => should log 'The slow, brown fox jumps over the lazy cats.'
// CHALLENGE 13
function createSecretHolder(secret) {
let mysecret = secret;
return {
getSecret: () => console.log(mysecret),
setSecret: (value) => mysecret = value
}
}
// /*** Uncomment these to check your work! ***/
let obj = createSecretHolder(5)
obj.getSecret() // => returns 5
obj.setSecret(2)
obj.getSecret() // => returns 2
// CHALLENGE 14
function callTimes() {
var count = 1;
return function(){
return console.log(count++);
}
}
// /*** Uncomment these to check your work! ***/
let myNewFunc1 = callTimes();
let myNewFunc2 = callTimes();
myNewFunc1(); // => 1
myNewFunc1(); // => 2
myNewFunc2(); // => 1
myNewFunc2(); // => 2
// CHALLENGE 15
function russianRoulette(num) {
var count = 0;
return function(){
count++;
if (count < num){
return 'click';
}
else if (count == num){
return 'bang';
}
else{
return 'reload to play again'
}
}
}
// /*** Uncomment these to check your work! ***/
const play = russianRoulette(3);
console.log(play()); // => should log 'click'
console.log(play()); // => should log 'click'
console.log(play()); // => should log 'bang'
console.log(play()); // => should log 'reload to play again'
console.log(play()); // => should log 'reload to play again'
// CHALLENGE 16
function average() {
var average = 0;
var count = 0;
return function(num=null){
if (num != null){
let total = (average*count) + num;
count++;
average = total/count;
}
return average;
}
}
// /*** Uncomment these to check your work! ***/
const avgSoFar = average();
console.log(avgSoFar()); // => should log 0
console.log(avgSoFar(4)); // => should log 4
console.log(avgSoFar(8)); // => should log 6
console.log(avgSoFar()); // => should log 6
console.log(avgSoFar(12)); // => should log 8
console.log(avgSoFar()); // => should log 8
// CHALLENGE 17
function makeFuncTester(arrOfTests) {
var array = [...arrOfTests];
return function(callback){
return array.every((value) => value[1] == callback(value[0]))
}
}
// /*** Uncomment these to check your work! ***/
const capLastTestCases = [];
capLastTestCases.push(['hello', 'hellO']);
capLastTestCases.push(['goodbye', 'goodbyE']);
capLastTestCases.push(['howdy', 'howdY']);
const shouldCapitalizeLast = makeFuncTester(capLastTestCases);
const capLastAttempt1 = str => str.toUpperCase();
const capLastAttempt2 = str => str.slice(0, -1) + str.slice(-1).toUpperCase();
console.log(shouldCapitalizeLast(capLastAttempt1)); // => should log false
console.log(shouldCapitalizeLast(capLastAttempt2)); // => should log true
// CHALLENGE 18
function makeHistory(limit) {
var storage = []
return function(value){
if (value == 'undo'){
if (storage.length == 0){
return 'nothing to undo';
}
else{
return storage.pop() + ' undone';
}
}
else{
storage.push(value)
if (storage.length > limit){
storage.shift();
}
return value + ' done';
}
}
}
// /*** Uncomment these to check your work! ***/
const myActions = makeHistory(2);
console.log(myActions('jump')); // => should log 'jump done'
console.log(myActions('undo')); // => should log 'jump undone'
console.log(myActions('walk')); // => should log 'walk done'
console.log(myActions('code')); // => should log 'code done'
console.log(myActions('pose')); // => should log 'pose done'
console.log(myActions('undo')); // => should log 'pose undone'
console.log(myActions('undo')); // => should log 'code undone'
console.log(myActions('undo')); // => should log 'nothing to undo'
// CHALLENGE 19
function blackjack(array) {
var index = 0;
return function(num1,num2){
var count = 0;
var currentTotal = 0;
return function(){
if (count == 0){
count++;
currentTotal = num1+num2;
return num1 + num2;
}
else if(currentTotal > 21){
return 'you are done!';
}
else{
currentTotal+=array[index]
index++;
if (currentTotal > 21){
return 'bust';
}
else{
return currentTotal;
}
}
}
}
}
// /*** Uncomment these to check your work! ***/
/*** DEALER ***/
const deal = blackjack([2, 6, 1, 7, 11, 4, 6, 3, 9, 8, 9, 3, 10, 4, 5, 3, 7, 4, 9, 6, 10, 11]);
/*** PLAYER 1 ***/
const i_like_to_live_dangerously = deal(4, 5);
console.log(i_like_to_live_dangerously()); // => should log 9
console.log(i_like_to_live_dangerously()); // => should log 11
console.log(i_like_to_live_dangerously()); // => should log 17
console.log(i_like_to_live_dangerously()); // => should log 18
console.log(i_like_to_live_dangerously()); // => should log 'bust'
console.log(i_like_to_live_dangerously()); // => should log 'you are done!'
console.log(i_like_to_live_dangerously()); // => should log 'you are done!'
// /*** BELOW LINES ARE FOR THE BONUS ***/
// /*** PLAYER 2 ***/
const i_TOO_like_to_live_dangerously = deal(2, 2);
console.log(i_TOO_like_to_live_dangerously()); // => should log 4
console.log(i_TOO_like_to_live_dangerously()); // => should log 15
console.log(i_TOO_like_to_live_dangerously()); // => should log 19
console.log(i_TOO_like_to_live_dangerously()); // => should log 'bust'
console.log(i_TOO_like_to_live_dangerously()); // => should log 'you are done!
console.log(i_TOO_like_to_live_dangerously()); // => should log 'you are done!
// // /*** PLAYER 3 ***/
const i_ALSO_like_to_live_dangerously = deal(3, 7);
console.log(i_ALSO_like_to_live_dangerously()); // => should log 10
console.log(i_ALSO_like_to_live_dangerously()); // => should log 13
console.log(i_ALSO_like_to_live_dangerously()); // => should log 'bust'
console.log(i_ALSO_like_to_live_dangerously()); // => should log 'you are done!
console.log(i_ALSO_like_to_live_dangerously()); // => should log 'you are done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment