shelving
Version:
Toolkit for using data in JavaScript.
54 lines (53 loc) • 1.82 kB
JavaScript
import { getFirst, getLast, omitArrayItems, requireArray, requireFirst, requireLast, toggleArrayItems, withArrayItems, } from "../util/array.js";
import { BusyStore } from "./BusyStore.js";
/** Store an array. */
export class ArrayStore extends BusyStore {
// Override to set default value to `[]` and convert possible arrays.
constructor(value = []) {
super(requireArray(value, undefined, undefined, ArrayStore));
}
// Implement to convert possible arrays.
_convert(input, caller) {
return requireArray(input, undefined, undefined, caller);
}
/** Get the first item in this store or `null` if this query has no items. */
get optionalFirst() {
return getFirst(this.value);
}
/** Get the last item in this store or `null` if this query has no items. */
get optionalLast() {
return getLast(this.value);
}
/** Get the first item in this store. */
get first() {
return requireFirst(this.value);
}
/** Get the last item in this store. */
get last() {
return requireLast(this.value);
}
/** Does the document have at least one result. */
get exists() {
return !!this.value.length;
}
/** Get the length of the current value of this store. */
get count() {
return this.value.length;
}
/** Add items to this array. */
add(...items) {
this.value = withArrayItems(this.value, ...items);
}
/** Remove items from this array. */
delete(...items) {
this.value = omitArrayItems(this.value, ...items);
}
/** Toggle items in this array. */
toggle(...items) {
this.value = toggleArrayItems(this.value, ...items);
}
/** Iterate over the items. */
[Symbol.iterator]() {
return this.value.values();
}
}