Skip to content

Commit 408d59a

Browse files
authored
Merge pull request #147 from nextcloud/enh/default-value
Add optional parameter to use as a default
2 parents d83034b + 7283775 commit 408d59a

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

lib/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
/**
22
* @param app app ID, e.g. "mail"
33
* @param key name of the property
4+
* @param fallback optional parameter to use as default value
45
* @throws if the key can't be found
56
*/
6-
export function loadState<T>(app: string, key: string): T {
7+
export function loadState<T>(app: string, key: string, fallback?: T): T {
78
const elem = <HTMLInputElement>document.querySelector(`#initial-state-${app}-${key}`)
89
if (elem === null) {
10+
if (fallback !== undefined) {
11+
return fallback
12+
}
913
throw new Error(`Could not find initial state ${key} of ${app}`)
1014
}
1115

test/index.test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ test('throw if nothing found', () => {
44
expect(() => loadState('test', 'key')).toThrow(new Error("Could not find initial state key of test"))
55
})
66

7+
test('return default if provided', () => {
8+
expect(loadState('test', 'key', 'default')).toBe('default')
9+
})
10+
711
test('find correct value', () => {
812
const input = document.createElement('input')
913
input.setAttribute('type', 'hidden')

0 commit comments

Comments
 (0)