All files / src/reactivity date.js

100% Statements 65/65
100% Branches 12/12
100% Functions 5/5
100% Lines 62/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 632x 2x 2x 2x 2x 2x 2x 2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 94x 58x 58x 179x 179x 179x 59x 208x 208x 208x 59x 59x 59x 59x 179x 179x 58x 58x 94x 94x 32x 32x 46x 46x 46x 46x 32x 32x 94x 2x 15x  
/** @import { Source } from '#client' */
import { derived } from '../internal/client/index.js';
import { source, set } from '../internal/client/reactivity/sources.js';
import { get } from '../internal/client/runtime.js';
 
var inited = false;
 
export class SvelteDate extends Date {
	#time = source(super.getTime());
 
	/** @type {Map<keyof Date, Source<unknown>>} */
	#deriveds = new Map();
 
	/** @param {any[]} params */
	constructor(...params) {
		// @ts-ignore
		super(...params);
		if (!inited) this.#init();
	}
 
	#init() {
		inited = true;
 
		var proto = SvelteDate.prototype;
		var date_proto = Date.prototype;
 
		var methods = /** @type {Array<keyof Date & string>} */ (
			Object.getOwnPropertyNames(date_proto)
		);
 
		for (const method of methods) {
			if (method.startsWith('get') || method.startsWith('to')) {
				// @ts-ignore
				proto[method] = function (...args) {
					var d = this.#deriveds.get(method);
 
					if (d === undefined) {
						d = derived(() => {
							get(this.#time);
							// @ts-ignore
							return date_proto[method].apply(this, args);
						});
 
						this.#deriveds.set(method, d);
					}
 
					return get(d);
				};
			}
 
			if (method.startsWith('set')) {
				// @ts-ignore
				proto[method] = function (...args) {
					// @ts-ignore
					var result = date_proto[method].apply(this, args);
					set(this.#time, date_proto.getTime.call(this));
					return result;
				};
			}
		}
	}
}