Skip to content

Recommended patterns for detecting and cloning any Temporal object #1841

@justingrant

Description

@justingrant

While testing Temporal in one of my apps, I ran into a failure that turned out to be caused by the clone library being unable to deep-clone objects that included Temporal instances as properties. Looking at the source of clone, it's clear why cloning won't work for Temporal instances. (Nor, I assume, with many other types like those that use private fields, WeakMaps, etc.)

There are a lot of similar libraries that do deep cloning. I assume that all of these libraries will need to be updated to know about Temporal, just like they needed to be updated to recognize other ES built-in types like Map and Set.

I assume it would be helpful for us to provide a recommended implementation of "Is this a Temporal instance?" and "clone this Temporal instance" code. I built a simplistic draft of these operations below. What am I missing?

In particular, is it better to identify "is this a Temporal instance" by comparing the constructor property to Temporal constructors? Or is it better to be more loose, like this?

o?.[Symbol.toStringTag] === 'Temporal.Instant'

Here's a starting point:

const temporalTypes = [
  Temporal.Instant,
  Temporal.ZonedDateTime,
  Temporal.PlainDate,
  Temporal.PlainTime,
  Temporal.PlainDateTime,
  Temporal.PlainYearMonth,
  Temporal.PlainMonthDay,
  Temporal.Duration,
  Temporal.TimeZone,
  Temporal.Calendar
];
function isTemporalInstance(o) {
  if (!o || !o.constructor) return false;
  return temporalTypes.includes(o.constructor);
}
function cloneTemporalInstance(o) {
  if (!o || !o.constructor) return undefined;
  const constructor = temporalTypes.find(t => t === o.constructor);
  return constructor ? constructor.from(o) : undefined;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationAdditions to documentation

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions