# misc/localstorage (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/localstorage/

로컬 스토리지.

## LocalStorage extends Object

로컬 스토리지.
- 기본 저장소는 브라우저의 window.localStorage 다. setBackend 로 다른 저장소(플랫폼 SDK 의 저장소 같은 것)로 갈아 끼울 수 있다.
- 모든 접근을 try 로 감싼다. 저장소가 막혀 있거나(사생활 보호 창, 막은 쿠키) 가득 차서 못 쓰면 예외를 내지 않고
  이 페이지가 살아 있는 동안 메모리에 대신 둔다. (그 값은 다시 켜면 없다, isMemoryFallback)
- 읽기(getString, getBoolean, getNumber, getJson)는 없는 키에 기본값을 써 넣지 않는다.

예제: 점수와 설정 저장하고 읽기

```js
import { LocalStorage } from "./build/vanilla.js";

LocalStorage.setNumber("example.bestScore", 1200);
LocalStorage.setBoolean("example.isMuted", true);
LocalStorage.setJson("example.settings", { volume: 0.8, language: "en" });
const bestScore = LocalStorage.getNumber("example.bestScore", 0);
const isMuted = LocalStorage.getBoolean("example.isMuted", false);
const settings = LocalStorage.getJson("example.settings", {});
console.log(bestScore, isMuted, settings.volume, LocalStorage.containsKey("example.bestScore"));
const removedCount = LocalStorage.clearByPrefix("example.");
console.log(removedCount, LocalStorage.isMemoryFallback());
```

- `constructor()` (constructor, since 0.1.0): 생성.
- `static setBackend(backend)` (static, since 0.4.0): 저장소 갈아 끼우기. (null 이면 브라우저 window.localStorage 로 돌아간다)
  - backend 는 getItem(key) → string | null, setItem(key, value), removeItem(key) 를 가진 객체다. (Storage 와 같은 꼴)
  - 키 목록(getKeys, clearByPrefix)과 전체 제거(clear)를 쓰려면 getKeys() → string[] 를, 한 번에 지우려면 clear() 를 더 둔다.
  - 갈아 끼우면 메모리에 대신 둔 값은 버린다.
  - `backend` { getItem: Function, setItem: Function, removeItem: Function, getKeys?: Function, clear?: Function } | null: 갈아 끼울 저장소. (null 이나 undefined 면 window.localStorage)

  예제: 내 저장소로 갈아 끼우기

  ```js
  import { LocalStorage } from "./build/vanilla.js";
  
  const itemMap = new Map();
  LocalStorage.setBackend({
  	getItem: (key) => {
  		return itemMap.has(key) ? itemMap.get(key) : null;
  	},
  	setItem: (key, value) => {
  		itemMap.set(key, value);
  	},
  	removeItem: (key) => {
  		itemMap.delete(key);
  	},
  	getKeys: () => {
  		return Array.from(itemMap.keys());
  	}
  });
  LocalStorage.setString("profile.name", "Player");
  console.log(itemMap.get("profile.name"), LocalStorage.getKeys());
  LocalStorage.setBackend(null);
  ```

- `static getBackend()` (static, since 0.4.0): 갈아 끼운 저장소 반환. (없으면 null)
  - returns object | null: 갈아 끼운 저장소. 없으면 null.
- `static setStorageDirectory(storageDirectoryPath)` (static, since 0.4.0): 저장 폴더 직접 설정. (러스트 판 데스크탑이 localstorage.json 을 둘 폴더, 원본은 브라우저가 페이지 주소마다 정해 아무것도 하지 않는다)
  - 같은 게임 코드가 두 엔진에서 돌게 두는 자리다. 러스트 판 웹도 아무것도 하지 않는다.
  - `storageDirectoryPath` string | null: localstorage.json 을 둘 폴더. (null 이면 앱 이름으로 정한 기본 폴더)

  예제: 저장 폴더를 정해도 원본 저장은 그대로 브라우저 저장소에 간다

  ```js
  import { LocalStorage } from "./build/vanilla.js";
  
  LocalStorage.setStorageDirectory("saves");
  LocalStorage.setString("profile.name", "Player");
  console.log(LocalStorage.getString("profile.name"));
  ```

- `static isMemoryFallback()` (static, since 0.4.0): 저장소를 못 써서 메모리로 대신한 적이 있는지.
  - returns boolean: 메모리로 대신한 적이 있으면 참. (setBackend 를 부르면 거짓으로 돌아간다)
- `static getItem(key)` (static, since 0.4.0): 값 하나 읽기. (없으면 null, 메모리에 대신 둔 값이 앞선다)
  - `key` string: 키.
  - returns string | null: 저장된 글. 없거나 못 읽으면 null.
- `static setItem(key, value)` (static, since 0.4.0): 값 하나 쓰기. (저장소에 썼으면 true, 못 써서 메모리에 대신 뒀으면 false)
  - `key` string: 키.
  - `value` string: 쓸 글.
  - returns boolean: 저장소에 썼으면 참. 메모리에 대신 뒀으면 거짓.
- `static removeItem(key)` (static, since 0.4.0): 값 하나 지우기. (메모리에 대신 둔 값도 지운다)
  - `key` string: 지울 키.
- `static clear()` (static, since 0.1.0): 전체 제거.
- `static setString(key, stringValue)` (static, since 0.1.0): 문자열 값 설정.
  - `key` string: 키.
  - `stringValue` string: 쓸 글.
- `static setBoolean(key, booleanValue)` (static, since 0.1.0): 논리 값 설정.
  - `key` string: 키.
  - `booleanValue` boolean: 쓸 값. ("true" 나 "false" 글로 쓴다)
- `static setNumber(key, numberValue)` (static, since 0.1.0): 숫자 값 설정.
  - `key` string: 키.
  - `numberValue` number: 쓸 값. (String 으로 바꿔 쓴다)
- `static remove(key)` (static, since 0.1.0): 값 제거.
  - `key` string: 지울 키.
- `static getString(key, defaultStringValue = "")` (static, since 0.1.0): 문자열 값 반환. (없으면 기본값, 저장소에는 쓰지 않는다)
  - `key` string: 키.
  - `defaultStringValue` string: 없을 때 돌려줄 값.
  - returns string: 저장된 글. 없으면 기본값.
- `static getBoolean(key, defaultBooleanValue = false)` (static, since 0.1.0): 논리 값 반환.
  - `key` string: 키.
  - `defaultBooleanValue` boolean: 없거나 빈 글일 때 돌려줄 값.
  - returns boolean: 저장된 글이 "true" 면 참. 없거나 빈 글이면 기본값.
- `static getNumber(key, defaultNumberValue = 0)` (static, since 0.1.0): 숫자 값 반환.
  - `key` string: 키.
  - `defaultNumberValue` number: 없거나 빈 글일 때 돌려줄 값.
  - returns number: 저장된 글을 Number 로 바꾼 값. (없거나 빈 글이면 기본값, 숫자가 아니면 NaN)
- `static clearByPrefix(prefix)` (static, since 0.3.0): 접두사로 시작하는 키 일괄 삭제. (정적)
  - 게임 네임스페이스의 저장 데이터를 통째로 지울 때 쓴다.
  - `prefix` string: 지울 키의 접두사. (빈 글이면 아무것도 지우지 않는다)
  - returns number: 지운 키 수.
- `static containsKey(key)` (static, since 0.1.0): 키가 있는지 반환. (메모리에 대신 둔 값도 본다)
  - `key` string: 찾을 키.
  - returns boolean: 값이 있으면 참.
- `static getKeys()` (static, since 0.1.0): 모든 키 반환.
  - returns string[]: 저장소와 메모리의 키를 합쳐 정렬한 배열.
- `static getJson(key, defaultValue = null)` (static, since 0.4.0): JSON 값 반환. (없거나 풀 수 없으면 기본값, 저장소에는 쓰지 않는다)
  - `key` string: 키.
  - `defaultValue` any: 없거나 빈 글이거나 풀 수 없을 때 돌려줄 값.
  - returns any: 풀어 낸 값. 없거나 풀 수 없으면 기본값.
- `static setJson(key, value)` (static, since 0.4.0): JSON 값 설정. (JSON 글로 바꿔 쓴다. 바꿀 수 없는 값(순환 참조 등)이면 쓰지 않고 false)
  - `key` string: 키.
  - `value` any: JSON 으로 바꿔 쓸 값.
  - returns boolean: 저장소에 썼는지. (메모리에 대신 뒀거나 바꿀 수 없으면 false)
