Created
May 15, 2021 21:10
-
-
Save helabenkhalfallah/c390fdd494a0381cdedbee5f1908dd7c to your computer and use it in GitHub Desktop.
JS Closure (Example 2)
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 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