Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created May 15, 2021 21:10
Show Gist options
  • Save helabenkhalfallah/c390fdd494a0381cdedbee5f1908dd7c to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/c390fdd494a0381cdedbee5f1908dd7c to your computer and use it in GitHub Desktop.
JS Closure (Example 2)
const playWithArray = () => {
let privateArray = [];
const addItem = (item) => {
privateArray.push(item);
}
const removeItem = (index) => {
privateArray.splice(index, 1);
}
return {
insert: (item) => {
addItem(item);
},
removeAtIndex: (index) => {
removeItem(index);
},
value: () => {
return privateArray;
}
};
};
const arrayApi = playWithArray();
console.log('arrayApi: ', arrayApi.value()); // []
arrayApi.insert('1');
arrayApi.insert('2');
arrayApi.insert('3');
arrayApi.insert('4');
console.log('arrayApi: ', arrayApi.value()); // ["1", "2", "3", "4"]
arrayApi.removeAtIndex(2);
console.log('arrayApi: ', arrayApi.value()); // ["1", "2", "4"]
arrayApi.removeAtIndex(2);
console.log('arrayApi: ', arrayApi.value()); // ["1", "2"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment