Created
February 1, 2023 21:30
-
-
Save brandonpapworth/402dd40eba8d4ada157d7377925cdacc to your computer and use it in GitHub Desktop.
Make a function that returns a number, starting with 1, increasing that number by 1 with each call of the function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// just using the module as the closure | |
let count = 1; | |
export function counter() { | |
return count++; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using a function to create a function with a counting variable | |
// scope accessible | |
function countingClosureCreator(startingNumber = 1) { | |
let count = startingNumber; | |
return function counter() { | |
return count++; | |
}; | |
} | |
export const counter = countingClosureCreator(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// just like counter2 but uses a self-executing | |
// function closure and arrow functions | |
export const counter = (() => { | |
let count = 1; | |
return () => count++; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Uses iterators for fun and profit | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* | |
function createInfiniteCountingIterator(startingNumber = 1) { | |
function* counterGenerator() { | |
let count = 1; | |
while (true) { | |
yield count++; | |
} | |
} | |
const iteratorInstance = counterGenerator(); | |
return iteratorInstance; | |
} | |
const infiniteCountingIterator = createInfiniteCountingIterator(); | |
export const counter = (() => { | |
return infiniteCountingIterator.next().value; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { counter } from './counter'; | |
console.log(counter()); // 1 | |
console.log(counter()); // 2 | |
console.log(counter()); // 3 | |
console.log(counter()); // 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment