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

Guess user timezone #285

Merged
merged 16 commits into from
Dec 28, 2015
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
806 changes: 403 additions & 403 deletions data/packed/latest.json

Large diffs are not rendered by default.

1,749 changes: 1,166 additions & 583 deletions data/unpacked/latest.json

Large diffs are not rendered by default.

58 changes: 43 additions & 15 deletions moment-timezone-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@
return abbrs.join(' ') + '|' + offsets.join(' ') + '|' + indices.join('');
}

function packPopulation (number) {
if (!number) {
return '';
}
if (number < 1000) {
return '|' + number;
}
var exponent = String(number | 0).length - 2;
var precision = Math.round(number / Math.pow(10, exponent));
return '|' + precision + 'e' + exponent;
}

function validatePackData (source) {
if (!source.name) { throw new Error("Missing name"); }
if (!source.abbrs) { throw new Error("Missing abbrs"); }
Expand All @@ -132,7 +144,11 @@

function pack (source) {
validatePackData(source);
return source.name + '|' + packAbbrsAndOffsets(source) + '|' + packUntils(source.untils);
return [
source.name,
packAbbrsAndOffsets(source),
packUntils(source.untils) + packPopulation(source.population)
].join('|');
}

/************************************
Expand All @@ -157,24 +173,35 @@
}

function findAndCreateLinks (input, output, links) {
var i, j, a, b, isUnique;
var i, j, a, b, group, foundGroup, groups = [];

for (i = 0; i < input.length; i++) {
isUnique = true;
foundGroup = false;
a = input[i];

for (j = 0; j < output.length; j++) {
b = output[j];

for (j = 0; j < groups.length; j++) {
group = groups[j];
b = group[0];
if (zonesAreEqual(a, b)) {
links.push(b.name + '|' + a.name);
isUnique = false;
continue;
if (a.population > b.population) {
group.unshift(a);
} else {
group.push(a);
}
foundGroup = true;
}
}

if (isUnique) {
output.push(a);
if (!foundGroup) {
groups.push([a]);
}
}

for (i = 0; i < groups.length; i++) {
group = groups[i];
output.push(group[0]);
for (j = 1; j < group.length; j++) {
links.push(group[0].name + '|' + group[j].name);
}
}
}
Expand Down Expand Up @@ -240,10 +267,11 @@
untils[untils.length - 1] = null;

return {
name : source.name,
abbrs : slice.apply(source.abbrs, indices),
untils : untils,
offsets : slice.apply(source.offsets, indices)
name : source.name,
abbrs : slice.apply(source.abbrs, indices),
untils : untils,
offsets : slice.apply(source.offsets, indices),
population : source.population
};
}

Expand Down
179 changes: 168 additions & 11 deletions moment-timezone.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
zones = {},
links = {},
names = {},
guesses = {},
cachedGuess,

momentVersion = moment.version.split('.'),
major = +momentVersion[0],
Expand Down Expand Up @@ -120,10 +122,11 @@
intToUntil(untils, indices.length);

return {
name : data[0],
abbrs : mapIndices(data[1].split(' '), indices),
offsets : mapIndices(offsets, indices),
untils : untils
name : data[0],
abbrs : mapIndices(data[1].split(' '), indices),
offsets : mapIndices(offsets, indices),
untils : untils,
population : data[5] | 0
};
}

Expand All @@ -139,10 +142,11 @@

Zone.prototype = {
_set : function (unpacked) {
this.name = unpacked.name;
this.abbrs = unpacked.abbrs;
this.untils = unpacked.untils;
this.offsets = unpacked.offsets;
this.name = unpacked.name;
this.abbrs = unpacked.abbrs;
this.untils = unpacked.untils;
this.offsets = unpacked.offsets;
this.population = unpacked.population;
},

_index : function (timestamp) {
Expand Down Expand Up @@ -192,6 +196,154 @@
}
};

/************************************
Current Timezone
************************************/

function OffsetAt(at) {
var timeString = at.toTimeString();
var abbr = timeString.match(/\(.+\)/);
if (abbr && abbr[0]) {
// 17:56:31 GMT-0600 (CST)
// 17:56:31 GMT-0600 (Central Standard Time)
abbr = abbr[0].match(/[A-Z]/g).join('');
} else {
// 17:56:31 CST
abbr = timeString.match(/[A-Z]{3,5}/g)[0];
}

if (abbr === 'GMT') {
abbr = undefined;
}

this.at = +at;
this.abbr = abbr;
this.offset = at.getTimezoneOffset();
}

function ZoneScore(zone) {
this.zone = zone;
this.offsetScore = 0;
this.abbrScore = 0;
}

ZoneScore.prototype.scoreOffsetAt = function (offsetAt) {
this.offsetScore += Math.abs(this.zone.offset(offsetAt.at) - offsetAt.offset);
if (this.zone.abbr(offsetAt.at).match(/[A-Z]/g).join('') !== offsetAt.abbr) {
this.abbrScore++;
}
};

function findChange(low, high) {
var mid, diff;

while ((diff = ((high.at - low.at) / 12e4 | 0) * 6e4)) {
mid = new OffsetAt(new Date(low.at + diff));
if (mid.offset === low.offset) {
low = mid;
} else {
high = mid;
}
}

return low;
}

function userOffsets() {
var startYear = new Date().getFullYear() - 2,
last = new OffsetAt(new Date(startYear, 0, 1)),
offsets = [last],
change, next, i;

for (i = 1; i < 48; i++) {
next = new OffsetAt(new Date(startYear, i, 1));
if (next.offset !== last.offset) {
change = findChange(last, next);
offsets.push(change);
offsets.push(new OffsetAt(new Date(change.at + 6e4)));
}
last = next;
}

for (i = 0; i < 4; i++) {
offsets.push(new OffsetAt(new Date(startYear + i, 0, 1)));
offsets.push(new OffsetAt(new Date(startYear + i, 6, 1)));
}

return offsets;
}

function sortZoneScores (a, b) {
if (a.offsetScore !== b.offsetScore) {
return a.offsetScore - b.offsetScore;
}
if (a.abbrScore !== b.abbrScore) {
return a.abbrScore - b.abbrScore;
}
return b.zone.population - a.zone.population;
}

function addToGuesses (name, offsets) {
var i, offset;
arrayToInt(offsets);
for (i = 0; i < offsets.length; i++) {
offset = offsets[i];
guesses[offset] = guesses[offset] || {};
guesses[offset][name] = true;
}
}

function guessesForUserOffsets (offsets) {
var offsetsLength = offsets.length,
filteredGuesses = {},
out = [],
i, j, guessesOffset;

for (i = 0; i < offsetsLength; i++) {
guessesOffset = guesses[offsets[i].offset] || {};
for (j in guessesOffset) {
if (guessesOffset.hasOwnProperty(j)) {
filteredGuesses[j] = true;
}
}
}

for (i in filteredGuesses) {
if (filteredGuesses.hasOwnProperty(i)) {
out.push(names[i]);
}
}

return out;
}

function rebuildGuess () {
var offsets = userOffsets(),
offsetsLength = offsets.length,
guesses = guessesForUserOffsets(offsets),
zoneScores = [],
zoneScore, i, j;

for (i = 0; i < guesses.length; i++) {
zoneScore = new ZoneScore(getZone(guesses[i]), offsetsLength);
for (j = 0; j < offsetsLength; j++) {
zoneScore.scoreOffsetAt(offsets[j]);
}
zoneScores.push(zoneScore);
}

zoneScores.sort(sortZoneScores);

return zoneScores.length > 0 ? zoneScores[0].zone.name : undefined;
}

function guess (ignoreCache) {
if (!cachedGuess || ignoreCache) {
cachedGuess = rebuildGuess();
}
return cachedGuess;
}

/************************************
Global Methods
************************************/
Expand All @@ -201,17 +353,21 @@
}

function addZone (packed) {
var i, name, normalized;
var i, name, split, normalized;

if (typeof packed === "string") {
packed = [packed];
}

for (i = 0; i < packed.length; i++) {
name = packed[i].split('|')[0];
split = packed[i].split('|');
name = split[0];
normalized = normalizeName(name);
zones[normalized] = packed[i];
names[normalized] = name;
if (split[5]) {
addToGuesses(normalized, split[2].split(' '));
}
}
}

Expand All @@ -220,7 +376,7 @@

var zone = zones[name];
var link;

if (zone instanceof Zone) {
return zone;
}
Expand Down Expand Up @@ -328,6 +484,7 @@
tz.load = loadData;
tz.zone = getZone;
tz.zoneExists = zoneExists; // deprecated in 0.1.0
tz.guess = guess;
tz.names = getNames;
tz.Zone = Zone;
tz.unpack = unpack;
Expand Down
13 changes: 8 additions & 5 deletions tasks/data-collect.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"use strict";

var path = require('path'),
moment = require('moment');
moment = require('moment'),
populations = require('./population.json');

module.exports = function (grunt) {
grunt.registerTask('data-collect', '4. Collect all data from zdump(8) into a single json file.', function (version) {
Expand All @@ -12,6 +13,7 @@ module.exports = function (grunt) {

files.forEach(function (file) {
var lines = grunt.file.read(path.join('temp/zdump/' + version, file)).split('\n'),
name = file.replace(/\.zdump$/, ''),
abbrs = [],
untils = [],
offsets = [];
Expand All @@ -30,10 +32,11 @@ module.exports = function (grunt) {
});

data.push({
name : file.replace(/\.zdump$/, ''),
abbrs : abbrs,
untils : untils,
offsets : offsets
name : name,
abbrs : abbrs,
untils : untils,
offsets : offsets,
population : populations[name] | 0
});
});

Expand Down
11 changes: 6 additions & 5 deletions tasks/data-dedupe.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ function dedupe(zone) {
}

return {
name : zone.name,
abbrs : abbrs,
untils : untils,
offsets : offsets
name : zone.name,
abbrs : abbrs,
untils : untils,
offsets : offsets,
population : zone.population
};
}

Expand Down Expand Up @@ -53,4 +54,4 @@ module.exports = function (grunt) {

grunt.log.ok('Deduped data for ' + version);
});
};
};
Loading