All files / src/reactivity date.js

100% Statements 62/62
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 631x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47x 29x 29x 145x 145x 145x 43x 162x 162x 162x 43x 43x 43x 43x 145x 145x 29x 29x 47x 47x 16x 16x 40x 40x 40x 40x 16x 16x 47x 1x 13x  
/** @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;
				};
			}
		}
	}
}