All files / src/reactivity date.js

100% Statements 75/75
100% Branches 16/16
100% Functions 5/5
100% Lines 71/71

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 63 64 65 66 67 68 69 70 71 722x 2x 2x 2x 2x 2x 2x 2x 2x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 94x 58x 58x 186x 186x 186x 2x 2x 2x 2x 184x 184x 184x 186x 62x 213x 213x 213x 62x 62x 62x 62x 184x 184x 58x 58x 94x 94x 32x 32x 48x 48x 48x 48x 32x 32x 94x 2x 17x  
/** @import { Source } from '#client' */
import { DESTROYED } from '../internal/client/constants.js';
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) {
					// don't memoize if there are arguments
					// @ts-ignore
					if (args.length > 0) {
						get(this.#time);
						// @ts-ignore
						return date_proto[method].apply(this, args);
					}
 
					var d = this.#deriveds.get(method);
 
					if (d === undefined || (d.f & DESTROYED) !== 0) {
						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;
				};
			}
		}
	}
}