Last active
October 29, 2021 17:04
Comparing lambda closure capturing in Python and javascript
This file contains hidden or 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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prints: