Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First go at a PolyFill #57

Merged
merged 3 commits into from
Jul 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
polyfill/index.js
polyfill/index.js.map
16 changes: 16 additions & 0 deletions polyfill/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Copyright 2018 Bloomberg LP

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 changes: 37 additions & 0 deletions polyfill/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Temporal Polyfill

This is an implementation of a polyfill for the [TC39 Termporal Proposal](https://github.com/tc39/proposal-temporal).

## Implementation Issues:

## Proposed Changes / Additions to the Proposal

### `Instant` constructor to take single `BigInt` argument

### `Instant.toDate()` & `Instant.fromDate()` for interoperability with `Date()`

### `Instant.prototype.valueOf()` & `ZonedInstant.prototype.valueOf()`

To facilitate comparisons between `Intant`s and/or `ZonedInstant`s it would be extremely useful to implement `valueOf()`.
Considering the fact that these have nanosecond precision, the proposed `[BigInt](https://github.com/tc39/proposal-bigint)`
seems to be the right choice of primitive.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes! I was reluctant to depend on bigint when it was early stage, but its done at this point.


### `Instant.prototype.toDate()` & `ZonedInstant.prototype.toDate()`

To facilitate better interoperation with existing `Date` APIs it would be useful to add a casting method to
`Instant` & `ZonedInstant`.

An example of such APIs would be the `Intl.DateTimeFormat` apis which work well with Dates, but not (yet?) with `Instant` &
`ZonedInstant`. Though for this specific case it might be better to add `format()` (see below).

### `Instant.prototype.format(locale = navigator.language, options = {})` & `ZonedInstant.prototype.format(locale = navigator.language, options = {})`

Considering the frequency of converting date/time values to customized strings, the `format` convenience method seems
to make sense. It should follow the same signature as `Intl.DateTimeFormat.prototype.format` with the notable exception
that `locale` ise defaulted to `navigator.language` and the `timeZone` option is overriddent to the `ZonedInstant`'s time
zone or UTC for `Instant`s.

### static `Instant.now()`

This would facilitate easier creation of Instant objects eliminating the need to work with `Date` objects. In addition,
when implemented natively, this would enable a higher precision timer.
50 changes: 50 additions & 0 deletions polyfill/lib/civildate.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
** Copyright (C) 2018 Bloomberg LP. All rights reserved.
** This code is governed by the license found in the LICENSE file.
*/

import { plus, pad } from './util.mjs';
import { CivilDateTime } from './civildatetime.mjs';

const DATA = Symbol('data');

export class CivilDate {
constructor(years, months, days) {
const { year, month, day } = plus({}, { years, months, days });
this[DATA] = { year, month, day };
}

get year() { return this[DATA].year; }
get month() { return this[DATA].month; }
get day() { return this[DATA].day; }

plus(data) {
const { year, month, day } = plus(this, data);
return new CivilDate(year, month, day);
}
with({ year = this.year, month = this.month , day = this.day } = {}) {
return new CivilDate(year, month, day);
}
withTime(time = CivilDateTime.now().toCivilTime()) {
return new CivilDateTime.from(this, time);
}
toString() {
const { year, month, day } = this;
return `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}`;
}

toDate(zone, time) {
return this.withTime(date).withZone(zone).toDate();
}

static now(zone) {
return CivilDateTime.now(zone).toCivilDate();
}
static fromDate(date, zone) {
return CivilDateTime.fromDate(date, zone).toCivilDate();
}

static parse(string) {
return CivilDateTime.parse(string).toCivilDate();
}
};
77 changes: 77 additions & 0 deletions polyfill/lib/civildatetime.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
** Copyright (C) 2018 Bloomberg LP. All rights reserved.
** This code is governed by the license found in the LICENSE file.
*/

import { plus, pad, parse } from './util.mjs';
import { toEpoch } from './epoch.mjs';
import { CivilDate } from './civildate.mjs';
import { CivilTime } from './civiltime.mjs';
import { VALUE, Instant } from './instant.mjs';
import { ZonedInstant } from './zonedinstant.mjs';

const DATA = Symbol('data');

export class CivilDateTime {
constructor(years, months, days, hours, minutes, seconds = 0, milliseconds = 0, nanoseconds = 0) {
this[DATA] = plus({}, { years, months, days, hours, minutes, seconds, milliseconds, nanoseconds });
}

get year() { return this[DATA].year; }
get month() { return this[DATA].month; }
get day() { return this[DATA].day; }
get hour() { return this[DATA].hour; }
get minute() { return this[DATA].minute; }
get second() { return this[DATA].second; }
get millisecond() { return this[DATA].millisecond; }
get nanosecond() { return this[DATA].nanosecond; }

plus(data) {
const { year, month, day, hour, minute, second, millisecond, nanosecond } = plus(this, data);
return new CivilDateTime(year, month, day, hour, minute, second, millisecond, nanosecond);
}
with({ year = this.year, month = this.month , day = this.day, hour = this.hour, minute = this.minute, second = this.second, millisecond = this.millisecond, nanosecond = this.nanosecond } = {}) {
return new CivilDateTime(year, month, day, hour, minute, second, millisecond, nanosecond);
}
toCivilDate() {
const { year, month, day } = this;
return new CivilDate(year, month, day);
}
toCivilTime() {
const { hour, minute, second, millisecond, nanosecond } = this;
return new CivilTime(hour, minute, second, millisecond, nanosecond);
}
withZone(zone) {
const milliseconds = toEpoch(this, zone);
const nanoseconds = this.nanosecond;
const instant = Object.create(Instant.prototype);
instant[VALUE] = { milliseconds, nanoseconds };
return new ZonedInstant(instant, zone);
}
toString() {
const { year, month, day, hour, minute, second, millisecond, nanosecond } = this;
const nanos = (millisecond * 1E6) + nanosecond;
return `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}T${pad(hour, 2)}:${pad(minute, 2)}:${pad(second, 2)}.${pad(nanos, 9)}`;
}

toDate(zone) {
return this.withZone(zone).toDate();
}

static from(date = {}, time = {}) {
const { year, month, day } = date;
const { hour, minute, second, millisecond, nanosecond } = time;
return new CivilDateTime(year, month, day, hour, minute, second, millisecond, nanosecond);
}
static now(zone) {
return ZonedInstant.now(zone).toCivilDateTime();
}
static fromDate(date, zone) {
return ZonedInstant.fromDate(date, zone).toCivilDateTime();
}

static parse(string) {
const { year, month, day, hour, minute, second, millisecond, nanosecond } = parse(string);
return new CivilDateTime(year, month, day, hour, minute, second, millisecond, nanosecond);
}
};
60 changes: 60 additions & 0 deletions polyfill/lib/civiltime.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
** Copyright (C) 2018 Bloomberg LP. All rights reserved.
** This code is governed by the license found in the LICENSE file.
*/

import { plus, pad } from './util.mjs';
import { CivilDateTime } from './civildatetime.mjs';
import { CivilDate } from './civildate.mjs';

const DATA = Symbol('data');

export class CivilTime {
constructor(hours, minutes, seconds = 0, milliseconds = 0, nanoseconds = 0) {
const { hour, minute, second, millisecond, nanosecond } = plus({}, { hours, minutes, seconds, milliseconds, nanoseconds });
this[DATA] = { hour, minute, second, millisecond, nanosecond };
}

get hour() { return this[DATA].hour; }
get minute() { return this[DATA].minute; }
get second() { return this[DATA].second; }
get millisecond() { return this[DATA].millisecond; }
get nanosecond() { return this[DATA].nanosecond; }

plus(data) {
const {
hour,
minute,
second,
millisecond,
nanosecond
} = plus(this, data);
return new CivilTime(hour, minute, second, millisecond, nanosecond);
}
with({ hour = this.hour, minute = this.minute, second = this.second, millisecond = this.millisecond, nanosecond = this.nanosecond } = {}) {
return new CivilTime(hour, minute, second, millisecond, nanosecond);
}
withDate(date = CivilDateTime.now().toCivilDate()) {
return new CivilDateTime.from(date, this);
}
toString() {
const { hour, minute, second, millisecond, nanosecond } = this;
const nanos = (millisecond * 1E6) + nanosecond;
return `${pad(hour, 2)}:${pad(minute, 2)}:${pad(second, 2)}.${pad(nanos, 9)}`;
}

toDate(zone, date) {
return this.withDate(date).withZone(zone).toDate();
}

static now(zone) {
return CivilDateTime.now(zone).toCivilTime();
}
static fromDate(date, zone) {
return CivilDateTime.fromDate(date, zone).toCivilTime();
}

static parse(string) {
return CivilDateTime.parse(string).toCivilTime();
}
}
117 changes: 117 additions & 0 deletions polyfill/lib/epoch.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
** Copyright (C) 2018 Bloomberg LP. All rights reserved.
** This code is governed by the license found in the LICENSE file.
*/

export function toEpoch({ year = 1970, month = 1, day = 1, hour = 0, minute = 0, second = 0, millisecond = 0 } = {}, zone) {
const ts = Date.UTC(year, month - 1, day, hour, minute, second, millisecond);

const offsetI = guessOffset(ts, zone);

const offsetA = guessOffset(ts + offsetI, zone);
if (checkOffset(ts + offsetA, zone, { year, month, day, hour, minute, second, millisecond })) {
return ts + offsetA;
}

const offsetB = guessOffset(ts - offsetI, zone);
if (checkOffset(ts + offsetB, zone, { year, month, day, hour, minute, second, millisecond })) {
return ts + offsetB;
}

return ts + Math.min(offsetA, offsetB);
}

export function fromEpoch(ts = 0, zone) {
const date = new Date(ts);
const fmt = formatter(zone);
const { year, month, day, hour, minute, second } = fmt.formatToParts(date).reduce((res, item)=>{
if (item.type !== 'literal') res[item.type] = parseInt(item.value, 10);
return res;
}, {});
return {
year, month, day,
hour, minute, second,
millisecond: date.getUTCMilliseconds()
};
}

export function zoneOffset(ts, zone) {
const offset = Math.floor(guessOffset(ts, zone) / 60000);
const sign = offset <= 0 ? '+' : '-';
const hours = ('00' + Math.floor(Math.abs(offset) / 60)).slice(-2);
const minutes = ('00' + Math.abs(offset % 60)).slice(-2);

return `${sign}${hours}:${minutes}`;
}

function guessOffset(ts, zone) {
const offset = fromEpoch(ts, zone);
const zoned = Date.UTC(offset.year, offset.month - 1, offset.day, offset.hour, offset.minute, offset.second, ts % 1000);
return ts - zoned;
}

function checkOffset(ts, zone, { year, month, day, hour, minute, second, millisecond }) {
const parts = fromEpoch(ts, zone);
return true &&
(year === parts.year) &&
(month === parts.month) &&
(day === parts.day) &&
(hour === parts.hour) &&
(minute === parts.minute) &&
(second === parts.second) &&
(millisecond === parts.millisecond);
}

function formatter(zone) {
if (zone === 'SYSTEM') {
return {
formatToParts: (date)=>[
{ type: 'year', value: '' + r.getFullYear() },
{ type: 'literal', value: '-' },
{ type: 'month', value: '' + (r.getMonth() + 1) },
{ type: 'literal', value: '-' },
{ type: 'day', value: '' + r.getDate() },
{ type: 'literal', value: ' ' },
{ type: 'hour', value: '' + r.getHours() },
{ type: 'literal', value: ':' },
{ type: 'minute', value: '' + r.getMinutes() },
{ type: 'literal', value: ':' },
{ type: 'second', value: '' + r.getSeconds() }
]
};
}
const parts = /([+-])(\d{1,2})(?::?(\d{2}))?/.exec(zone);
if (parts) {
const minutes = (+parts[2] * 60) + (parts[3] || 0);
const offset = (parts[1] === '-') ? -minutes : +minutes;
return {
formatToParts: (date)=>{
const ts = date.valueOf() - offset;
const r = new Date(ts);
return [
{ type: 'year', value: '' + r.getUTCFullYear() },
{ type: 'literal', value: '-' },
{ type: 'month', value: '' + (r.getUTCMonth() + 1) },
{ type: 'literal', value: '-' },
{ type: 'day', value: '' + r.getUTCDate() },
{ type: 'literal', value: ' ' },
{ type: 'hour', value: '' + r.getUTCHours() },
{ type: 'literal', value: ':' },
{ type: 'minute', value: '' + r.getUTCMinutes() },
{ type: 'literal', value: ':' },
{ type: 'second', value: '' + r.getUTCSeconds() }
];
}
};
}
return new Intl.DateTimeFormat('en-iso', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZone: zone
});
}
10 changes: 10 additions & 0 deletions polyfill/lib/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
** Copyright (C) 2018 Bloomberg LP. All rights reserved.
** This code is governed by the license found in the LICENSE file.
*/

export { CivilDate } from './civildate.mjs';
export { CivilTime } from './civiltime.mjs';
export { CivilDateTime } from './civildatetime.mjs';
export { Instant } from './instant.mjs';
export { ZonedInstant } from './zonedinstant.mjs';
Loading