Skip to content

Instantly share code, notes, and snippets.

@brandonpapworth
Created February 1, 2023 21:30
Show Gist options
  • Save brandonpapworth/402dd40eba8d4ada157d7377925cdacc to your computer and use it in GitHub Desktop.
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
// just using the module as the closure
let count = 1;
export function counter() {
return count++;
}
// 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();
// just like counter2 but uses a self-executing
// function closure and arrow functions
export const counter = (() => {
let count = 1;
return () => count++;
})();
// 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;
})();
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