Skip to content

Instantly share code, notes, and snippets.

@kristof-mattei
Last active October 29, 2021 17:04
Show Gist options
  • Save kristof-mattei/e29df7eccf98b9a20833ac655832519c to your computer and use it in GitHub Desktop.
Save kristof-mattei/e29df7eccf98b9a20833ac655832519c to your computer and use it in GitHub Desktop.
Comparing lambda closure capturing in Python and javascript
const max = 3;
function get_functions() {
lst = []
for (const i of [...Array(max).keys()]) {
lst.push(() => i)
}
return lst
}
function* get_functions_yield() {
for (const i of [...Array(max).keys()]) {
yield (() => i);
}
}
function* get_functions_yield_separate_var() {
for (const i of [...Array(max).keys()]) {
x = i
yield (() => x)
}
}
function* get_functions_yield_separate_context() {
for (const i of [...Array(max).keys()]) {
yield ((x => () => x)(i))
}
}
function* for_f(iterator) {
for (const f of iterator()) {
yield f()
}
}
function* for_f_preload(iterator) {
for (const f of [...iterator()]) {
yield f()
}
}
// functions:
functions = [
get_functions,
get_functions_yield,
get_functions_yield_separate_var,
get_functions_yield_separate_context,
]
// iterations
iterations = [
for_f,
for_f_preload
]
const table = {};
for (const f of functions) {
for (const i of iterations) {
table[i.name] = {
...table[i.name],
[f.name]: [...i(f)]
}
}
}
console.table(table);
@kristof-mattei
Copy link
Author

kristof-mattei commented Oct 13, 2020

Prints:

┌───────────────┬───────────────┬─────────────────────┬──────────────────────────────────┬──────────────────────────────────────┐
│    (index)    │ get_functions │ get_functions_yield │ get_functions_yield_separate_var │ get_functions_yield_separate_context │
├───────────────┼───────────────┼─────────────────────┼──────────────────────────────────┼──────────────────────────────────────┤
│     for_f     │  [ 0, 1, 2 ]  │     [ 0, 1, 2 ]     │           [ 0, 1, 2 ]            │             [ 0, 1, 2 ]              │
│ for_f_preload │  [ 0, 1, 2 ]  │     [ 0, 1, 2 ]     │           [ 2, 2, 2 ]            │             [ 0, 1, 2 ]              │
└───────────────┴───────────────┴─────────────────────┴──────────────────────────────────┴──────────────────────────────────────┘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment