Skip to content

Instantly share code, notes, and snippets.

@Ciantic
Last active September 19, 2021 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ciantic/3ffbdf4e6f28f888e790e2d0a66d1451 to your computer and use it in GitHub Desktop.
Save Ciantic/3ffbdf4e6f28f888e790e2d0a66d1451 to your computer and use it in GitHub Desktop.
ObservableMap (from MobX) to solidjs (not sure if this is a good idea)
// LICENSE MIT, Jari Pennanen
// For all purposes, I also consider this public domain work.
import { untrack } from "solid-js";
import { createStore } from "solid-js/store";
/**
* Solid JS
*
* @returns Map like observable
*/
export function createObservableMap<Key extends string | number, Value>(): Map<Key, Value> {
// Some reason in following [k: Key] does not work?
const [get, set] = createStore({} as { [k: string]: Value });
return {
delete(k: Key) {
const ok = k in get;
set(k as any, undefined as any);
return ok;
},
set(k: Key, v: Value) {
set(k, v);
return this;
},
get(k: Key): Value | undefined {
return get[k as any];
},
clear() {
const keys = untrack(() => {
return this.keys();
});
for (const key of keys) {
set(key, undefined as any);
}
},
forEach(cb) {
for (const key in get) {
if (Object.prototype.hasOwnProperty.call(get, key)) {
const element = get[key];
cb(element, key as any, this);
}
}
},
has(key: Key) {
return key in get;
},
get size() {
return Object.keys(get).length;
},
entries() {
const v = get;
const e = Object.entries(v) as any as [Key, Value][];
const i = e[Symbol.iterator]();
return i;
},
keys() {
const k = Object.keys(get) as any as Key[];
const i = k[Symbol.iterator]();
return i;
},
values() {
const k = Object.values(get);
const i = k[Symbol.iterator]();
return i;
},
[Symbol.iterator]() {
return this.entries();
},
[Symbol.toStringTag]: "ObservableMap",
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment