import { proxyStorage } from './proxyStorage' ; export function scopeStorage ( scope , storage ) { return proxyStorage ( createScopedStorage ( scope , storage ) ) ; } function createScopedStorage ( scope , storage ) { let scopedKeys = getAllKeysInScope ( scope , storage ) ; const getScopedKey = ( key ) => `${ scope }-${ key }` ; const getItem = ( key ) => storage . getItem ( getScopedKey ( key ) ) ; const setItem = ( key , value ) => { const scopedKey = getScopedKey ( key ) ; if ( scopedKeys . indexOf ( scopedKey ) === - 1 ) { scopedKeys . push ( scopedKey ) ; } return storage . setItem ( scopedKey , value ) ; } ; const removeItem = ( key ) => { const scopedKey = getScopedKey ( key ) ; const index = scopedKeys . indexOf ( scopedKey ) ; if ( index > - 1 ) { scopedKeys . splice ( index ) ; } return storage . removeItem ( scopedKey ) ; } ; const clear = ( ) => { scopedKeys . forEach ( ( key ) => storage . removeItem ( key ) ) ; scopedKeys = [ ] ; } ; const key = ( i ) => scopedKeys [ i ] ; return { getItem , setItem , removeItem , clear , get length ( ) { return scopedKeys . length ; } , key , } ; } function getAllKeysInScope ( scope , storage ) { const scopedKeys = [ ] ; for ( let i = 0 ; i < storage . length ; ++ i ) { const key = localStorage . key ( i ) ! ; if ( key . indexOf ( scope ) === 0 ) { scopedKeys . push ( key ) ; } } return scopedKeys ; }