Created
April 20, 2021 16:20
-
-
Save nelsonfncosta/1b51f95c76c21fb3aae71142c5ccd5ac to your computer and use it in GitHub Desktop.
Example of how closures can help with memory management
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
function findCustomerCity(name) { | |
const texasCustomers = ['John', 'Ludwig', 'Kate']; | |
const californiaCustomers = ['Wade', 'Lucie','Kylie']; | |
return texasCustomers.includes(name) ? 'Texas' : | |
californiaCustomers.includes(name) ? 'California' : 'Unknown'; | |
}; | |
// For every call, memory is unnecessarily re-allocated to the variables texasCustometrs and californiaCustomers . | |
function findCustomerCity() { | |
const texasCustomers = ['John', 'Ludwig', 'Kate']; | |
const californiaCustomers = ['Wade', 'Lucie','Kylie']; | |
return name => texasCustomers.includes(name) ? 'Texas' : | |
californiaCustomers.includes(name) ? 'California' : 'Unknown'; | |
}; | |
let cityOfCustomer = findCustomerCity(); | |
cityOfCustomer('John');//Texas | |
cityOfCustomer('Wade');//California | |
cityOfCustomer('Max');//Unknown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment