Created
January 30, 2023 18:16
-
-
Save mortyobnoxious/8f2c107c8d5aee911575ba4ce139fbc1 to your computer and use it in GitHub Desktop.
Tampermonkey Storage class by ChatGPT
This file contains 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
/* by ChatGPT | |
storage class for tampermonkey | |
GM_setValue | |
GM_getValue | |
GM_deleteValue | |
Example users array with objects: | |
"users": [ | |
{ | |
"user": "username", | |
"info": "info" | |
}, | |
] | |
*/ | |
class TampermonkeyStorage { | |
constructor(key) {this.key = key;} | |
modify(index, value) { | |
let values = this.values; | |
index === -1 | |
? values.push(value) | |
: value | |
? (values[index] = value) | |
: values.splice(index, 1); | |
GM_setValue(this.key, values); | |
} | |
removeAll() {GM_deleteValue(this.key);} | |
findIndex(key, value) {return this.values.findIndex(key && value ? obj => obj[key] === value : item => item === key);} | |
move(index, direction) { | |
const values = this.values; | |
const newIndex = (index + direction + values.length) % values.length; | |
const [item] = values.splice(index, 1); | |
values.splice(newIndex, 0, item); | |
GM_setValue(this.key, values); | |
} | |
get values() {return GM_getValue(this.key) || []} | |
} | |
/* Usage */ | |
// create it like this (this will create a users array) | |
const usersGM = new TampermonkeyStorage('users'); | |
// add data like this: | |
let data = {user: 'username', info: 'info'}; | |
// this will find index if data.username exists and update it, if not it will create a new one | |
let index = usersGM.findIndex('user', data.username); | |
usersGM.modify(index, data); | |
// another way to add data | |
let anotherData = {user: 'anotherUser', info: 'info'} | |
usersGM.modify(-1, anotherData); // this will add user if it exists or not | |
// delete data by index | |
let indextoDelete = usersGM.findIndex('user', 'userNametoDelete'); | |
usersGM.modify(indextoDelete); | |
// get all the values | |
let values = usersGM.values; | |
// delete key | |
usersGM.removeAll(); | |
// you move data inside users array up and down | |
let indextoMove = usersGM.findIndex('user', 'userNametoMove'); | |
let moveUP = -1; | |
let moveDown = 1; | |
usersGM.move(indextoMove, moveUP); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: