Skip to content

Instantly share code, notes, and snippets.

@mortyobnoxious
Created January 30, 2023 18:16
Show Gist options
  • Save mortyobnoxious/8f2c107c8d5aee911575ba4ce139fbc1 to your computer and use it in GitHub Desktop.
Save mortyobnoxious/8f2c107c8d5aee911575ba4ce139fbc1 to your computer and use it in GitHub Desktop.
Tampermonkey Storage class by ChatGPT
/* 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);
@mortyobnoxious
Copy link
Author

Usage:

// Creating an instance:
const storage = new TampermonkeyStorage("myKey");

// Adding an item to storage:
storage.modify(-1, {name: "John Doe", age: 30});

// Updating an item in storage:
const index = storage.findIndex("name", "John Doe");
storage.modify(index, {name: "Jane Doe", age: 31});

// Removing an item from storage:
const index = storage.findIndex("Jane Doe");
storage.modify(index);

// Removing all items from storage:
storage.removeAll();

// Moving an item within the storage:
const index = storage.findIndex("Jane Doe");
storage.move(index, -1); // move up
storage.move(index, 1); // move down

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment