Skip to content

Instantly share code, notes, and snippets.

@zeuschild
Created September 10, 2017 12:41
Show Gist options
  • Save zeuschild/9a105d28fe37e9e30a39c3ba3484b977 to your computer and use it in GitHub Desktop.
Save zeuschild/9a105d28fe37e9e30a39c3ba3484b977 to your computer and use it in GitHub Desktop.
Oursky Developer Pre-Test

//createArrayOfFunctions

function createArrayOfFunctions(y) {

var arr = [];

for(var i = 0; i<y; i++) {

arr[i] = function(x) { return x + i; }

}

return arr;

}

We plan to use the Javascript function above to create an array and fill value for each elements of it but the function doesn't work as expected. To correct it, we need the help of closure. The function is rewritten as following:

//Fix bug in create array function

function createArrayOfFunctions(y) {

var arr = [];

for(var i = 0; i<y; i++) {

arr[i] = function(x) { return x + i; }(i);

}

return arr;

}

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