UNPKG

melt

Version:

The next generation of Melt UI. Built for Svelte 5.

124 lines (123 loc) 3.05 kB
export class Collection { source; defaultValue; constructor(source, defaultValue) { this.source = source; this.defaultValue = defaultValue; } getIterable() { if (!this.source) { return this.defaultValue !== undefined ? this.defaultValue : []; } return typeof this.source === "function" ? this.source() : this.source; } *[Symbol.iterator]() { const iterable = this.getIterable(); if (iterable) { yield* iterable; } } *keys() { const iterable = this.getIterable(); if (iterable) { let index = 0; for (const _ of iterable) { yield index++; } } } *values() { const iterable = this.getIterable(); if (iterable) { yield* iterable; } } *entries() { const iterable = this.getIterable(); if (iterable) { let index = 0; for (const value of iterable) { yield [index++, value]; } } } toArray() { const iterable = this.getIterable(); return iterable ? Array.from(iterable) : []; } toSet() { const iterable = this.getIterable(); return new Set(iterable); } size() { const iterable = this.getIterable(); if (!iterable) return 0; let count = 0; for (const _ of iterable) { count++; } return count; } isEmpty() { const iterable = this.getIterable(); if (!iterable) return true; for (const _ of iterable) { return false; } return true; } first() { const iterable = this.getIterable(); if (!iterable) return undefined; for (const value of iterable) { return value; } return undefined; } last() { const iterable = this.getIterable(); if (!iterable) return undefined; let lastValue; for (const value of iterable) { lastValue = value; } return lastValue; } find(predicate) { const iterable = this.getIterable(); if (!iterable) return undefined; for (const value of iterable) { if (predicate(value)) { return value; } } return undefined; } some(predicate) { const iterable = this.getIterable(); if (!iterable) return false; for (const value of iterable) { if (predicate(value)) { return true; } } return false; } every(predicate) { const iterable = this.getIterable(); if (!iterable) return true; for (const value of iterable) { if (!predicate(value)) { return false; } } return true; } }