Greasy Fork

Shined up real nice.

SingletonData

try to take over the world!

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://greasyfork.org/scripts/31539-singletondata/code/SingletonData.js?version=212334

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// ==UserScript==
// @name               SingletonData
// @namespace          https://github.com/cologler/
// @version            0.3
// @description        try to take over the world!
// @author             cologler
// @grant              GM_getValue
// @grant              GM_setValue
// @grant              GM_addValueChangeListener
// @grant              GM_removeValueChangeListener
// ==/UserScript==

// just let type script work.
(function() { function require(){}; require("greasemonkey"); })();

let SingletonData = (() => {
    let names = new Set();
    class SingletonData {
        constructor(key, defaultValue = null) {
            if (typeof key !== 'string') throw 'key must be string';
            if (!key) throw 'key cannot be empty';
            if (names.has(key)) throw `SingletonData <${key}> is created.`;
            names.add(key);

            const unset = {};
            let data = unset;
            let isDisposed = false;

            function ensureSafe() {
                if (isDisposed) throw 'object is disposed.';
            }

            Object.defineProperty(this, 'data', {
                get: () => {
                    ensureSafe();
                    if (data === unset) {
                        data = GM_getValue(key, defaultValue);
                    }
                    return data;
                },
                set: value => {
                    ensureSafe();
                    data = value;
                    GM_setValue(key, value);
                }
            });

            this.save = () => {
                ensureSafe();
                GM_setValue(key, data);
            };

            const listenerId = GM_addValueChangeListener(key, (_, oldValue, newValue, remote) => {
                if (!remote) return;
                data = newValue;
            });
            this.dispose = () => {
                isDisposed = true;
                GM_removeValueChangeListener(listenerId);
                names.delete(key);
            };
        }
    }

    return SingletonData;
})();