I don't understand the intuition of closures and they turn me off to languages immediately. They feel like a hack from someone who didn't want to store a copy of a parent-scope variable within a function. The idea that I can touch variables that have gone out of scope (and that have ostensibly been GC'd) makes me feel that it is impossible to reason about variable lifetimes when dealing with closures. Is there some p…
const Counter = () => {
let counts = new Map();
return {
reset: () => {
counts = new Map();
},
count: (key) => {
const count = counts.get(key) + 1;
counts.set(key, count);
return count;
}
}
}
const items = ['apple', 'apple', 'banana', 'canteloupe'];
const counter = Counter()
items.forEach(item => {
console.log(item + ": count is", counter.count(item));
})
counter.reset();
// do some more counting now
IMO, this is much simpler [and prettier ;)] than the alternative using classes: you only need to know closures and objects, and the rules apply the same as they do in all other contexts. Classes in most languages usually come with their own twists and surprises.