clean up utilities

This commit is contained in:
Matt Walsh 2020-09-24 19:38:53 -05:00
parent 998a869ca0
commit 34e7775838
4 changed files with 21 additions and 425 deletions

File diff suppressed because one or more lines are too long

View file

@ -28,8 +28,8 @@ class LocalForecast extends WeatherDisplay {
const conditions = this.parseLocalForecast(rawData);
// split this forecast into the correct number of screens
const MaxRows = 7;
const MaxCols = 32;
const maxRows = 7;
const maxCols = 32;
this.screenTexts = [];
@ -43,23 +43,23 @@ class LocalForecast extends WeatherDisplay {
}
text += conditionText.toUpperCase().replace('...', ' ');
text = text.wordWrap(MaxCols, '\n');
const Lines = text.split('\n');
const LineCount = Lines.length;
text = utils.string.wordWrap(text, maxCols, '\n');
const lines = text.split('\n');
const lineCount = lines.length;
let ScreenText = '';
const MaxRowCount = MaxRows;
let RowCount = 0;
const maxRowCount = maxRows;
let rowCount = 0;
// if (PrependAlert) {
// ScreenText = LocalForecastScreenTexts[LocalForecastScreenTexts.length - 1];
// RowCount = ScreenText.split('\n').length - 1;
// rowCount = ScreenText.split('\n').length - 1;
// }
for (let i = 0; i <= LineCount - 1; i++) {
if (Lines[i] === '') continue;
for (let i = 0; i <= lineCount - 1; i++) {
if (lines[i] === '') continue;
if (RowCount > MaxRowCount - 1) {
if (rowCount > maxRowCount - 1) {
// if (PrependAlert) {
// LocalForecastScreenTexts[LocalForecastScreenTexts.length - 1] = ScreenText;
// PrependAlert = false;
@ -67,11 +67,11 @@ class LocalForecast extends WeatherDisplay {
this.screenTexts.push(ScreenText);
// }
ScreenText = '';
RowCount = 0;
rowCount = 0;
}
ScreenText += Lines[i] + '\n';
RowCount++;
ScreenText += lines[i] + '\n';
rowCount++;
}
// if (PrependAlert) {
// this.screenTexts[this.screenTexts.length - 1] = ScreenText;

View file

@ -145,222 +145,11 @@ const utils = (() => {
// wrap a number to 0-m
const wrap = (x,m) => (x%m + m)%m;
// ********************************* date functions ***************************
const getDateFromUTC = (date, utc) => {
const time = utc.split(':');
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), time[0], time[1], 0));
};
const getTimeZoneOffsetFromUTC = (timezone) => {
switch (timezone) {
case 'EST':
return -5;
case 'EDT':
return -4;
case 'CST':
return -6;
case 'CDT':
return -5;
case 'MST':
return -7;
case 'MDT':
return -6;
case 'PST':
return -8;
case 'PDT':
return -7;
case 'AST':
case 'AKST':
return -9;
case 'ADT':
case 'AKDT':
return -8;
case 'HST':
return -10;
case 'HDT':
return -9;
default:
return null;
}
};
Date.prototype.getTimeZone = function () {
const tz = this.toLocaleTimeString('en-us', { timeZoneName: 'short' }).split(' ')[2];
if (tz === null){
switch (this.toTimeString().split(' ')[2]) {
case '(Eastern':
return 'EST';
case '(Central':
return 'CST';
case '(Mountain':
return 'MST';
case '(Pacific':
return 'PST';
case '(Alaskan':
return 'AST';
case '(Hawaiian':
return 'HST';
default:
}
} else if (tz.length === 4) {
// Fix weird bug in Edge where it returns the timezone with a null character in the first position.
return tz.substr(1);
}
return tz;
};
Date.prototype.addHours = function (hours) {
var dat = new Date(this.valueOf());
dat.setHours(dat.getHours() + hours);
return dat;
};
Date.prototype.getDayShortName = function () {
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
return days[this.getDay()];
};
Date.prototype.getMonthShortName = function () {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return months[this.getMonth()];
};
const dateToTimeZone = (date, timezone) => {
const OldOffset = getTimeZoneOffsetFromUTC(date.getTimeZone());
const NewOffset = getTimeZoneOffsetFromUTC(timezone);
let dt = new Date(date);
dt = dt.addHours(OldOffset * -1);
dt = dt.addHours(NewOffset);
return dt;
};
const getDateFromTime = (date, time, timezone) => {
const Time = time.split(':');
if (timezone) {
const Offset = getTimeZoneOffsetFromUTC(timezone) * -1;
const newDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), Time[0], Time[1], 0));
return newDate.addHours(Offset);
} else {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), Time[0], Time[1], 0);
}
};
Date.prototype.getFormattedTime = function () {
let hours;
let minutes;
let ampm;
switch (_Units) {
case Units.English:
hours = this.getHours() === 0 ? '12' : this.getHours() > 12 ? this.getHours() - 12 : this.getHours();
minutes = (this.getMinutes() < 10 ? '0' : '') + this.getMinutes();
ampm = this.getHours() < 12 ? 'am' : 'pm';
return hours + ':' + minutes + ' ' + ampm;
default:
hours = (this.getHours() < 10 ? ' ' : '') + this.getHours();
minutes = (this.getMinutes() < 10 ? '0' : '') + this.getMinutes();
return hours + ':' + minutes;
}
};
Date.prototype.toTimeAMPM = function () {
const date = this;
let hours = date.getHours();
let minutes = date.getMinutes();
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ' ' + ampm;
};
const xmlDateToJsDate = (XmlDate) => {
let bits = XmlDate.split(/[-T:+]/g);
if (bits[5] === undefined) {
console.log('bit[5] is undefined');
}
bits[5] = bits[5].replace('Z', '');
const d = new Date(bits[0], bits[1] - 1, bits[2]);
d.setHours(bits[3], bits[4], bits[5]);
// Case for when no time zone offset if specified
if (bits.length < 8) {
bits.push('00');
bits.push('00');
}
// Get supplied time zone offset in minutes
const sign = /\d\d-\d\d:\d\d$/.test(XmlDate) ? '-' : '+';
const offsetMinutes = (sign==='-'?-1:1)*(bits[6] * 60 + Number(bits[7]));
// Apply offset and local timezone
// d is now a local time equivalent to the supplied time
return d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset());
};
const timeTo24Hour = (Time) => {
const AMPM = Time.substr(Time.length - 2);
const MM = Time.split(':')[1].substr(0, 2);
let HH = Time.split(':')[0];
switch (AMPM.toLowerCase()) {
case 'am':
if (HH === '12') HH = '0';
break;
case 'pm':
if (HH !== '12') HH = (parseInt(HH) + 12).toString();
break;
default:
}
return HH + ':' + MM;
};
// compare objects on shallow equality (nested objects ignored)
const shallowEqual= (obj1, obj2) => {
if (typeof obj1 !== 'object') return false;
if (typeof obj2 !== 'object') return false;
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
for (const key of keys1) {
if (typeof obj1[key] !== 'object' && obj1[key] !== obj2[key]) return false;
}
return true;
};
// ********************************* strings *********************************************
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
String.prototype.wordWrap = function () {
let str = this;
let m = ((arguments.length >= 1) ? arguments[0] : 75);
let b = ((arguments.length >= 2) ? arguments[1] : '\n');
let c = ((arguments.length >= 3) ? arguments[2] : false);
const wordWrap = (str, ...rest) => {
let m = ((rest.length >= 1) ? rest[0] : 75);
let b = ((rest.length >= 2) ? rest[1] : '\n');
let c = ((rest.length >= 3) ? rest[2] : false);
let i, j, l, s, r;
@ -415,16 +204,8 @@ const utils = (() => {
distance,
wrap,
},
dateTime: {
getDateFromUTC,
getTimeZoneOffsetFromUTC,
dateToTimeZone,
getDateFromTime,
xmlDateToJsDate,
timeTo24Hour,
},
object: {
shallowEqual,
string: {
wordWrap,
},
};
})();

View file

@ -1,9 +1,6 @@
/* globals _StationInfo, luxon, _RegionalCities, utils, icons, _TravelCities, SunCalc */
const _DayShortNames = { 'Sunday': 'Sun', 'Monday': 'Mon', 'Tuesday': 'Tue', 'Wednesday': 'Wed', 'Thursday': 'Thu', 'Friday': 'Fri', 'Saturday': 'Sat' };
var canvasProgress;
var divProgress;
var canvasRegionalObservations;
var canvasRegionalForecast1;
@ -39,28 +36,10 @@ var canvasLatestObservations;
var _WeatherParameters = null;
var LoadStatuses = {
Loading: 0,
Loaded: 1,
Failed: 2,
NoData: 3,
};
var _UpdateWeatherUpdateMs = 50;
var canvasBackGroundDateTime = null;
var canvasBackGroundCurrentConditions = null;
var CurrentConditionTypes = {
Title: 0,
Conditions: 1,
Temperature: 2,
HumidityDewpoint: 3,
BarometricPressure: 4,
Wind: 5,
VisibilityCeiling: 6,
MonthPrecipitation: 7,
};
var _UpdateWeatherCurrentConditionType = CurrentConditionTypes.Title;
var _UpdateWeatherCurrentConditionCounterMs = 0;
@ -68,54 +47,6 @@ var _UpdateCustomScrollTextMs = 0;
var _UpdateHazardsY = 0;
var CanvasTypes = {
Progress: 0,
CurrentWeather: 1,
LatestObservations: 2,
TravelForecast: 3,
RegionalForecast1: 4,
RegionalForecast2: 5,
RegionalObservations: 6,
LocalForecast: 7,
MarineForecast: 8,
ExtendedForecast1: 9,
ExtendedForecast2: 10,
Almanac: 11,
AlmanacTides: 12,
AirQuality: 13,
Outlook: 14,
LocalRadar: 15,
Hazards: 16,
};
var _FirstCanvasType = CanvasTypes.Progress;
var _CurrentCanvasType = _FirstCanvasType;
var _IsPlaying = false;
const OperatingSystems = {
Unknown: 0,
Windows: 1,
MacOS: 2,
Linux: 3,
Unix: 4,
iOS: 5,
Andriod: 6,
WindowsPhone: 7,
};
let _OperatingSystem = OperatingSystems.Unknown;
const _UserAgent = window.navigator.userAgent;
if (_UserAgent.indexOf('Win') !== -1) _OperatingSystem = OperatingSystems.Windows;
if (_UserAgent.indexOf('Mac') !== -1) _OperatingSystem = OperatingSystems.MacOS;
if (_UserAgent.indexOf('X11') !== -1) _OperatingSystem = OperatingSystems.Unix;
if (_UserAgent.indexOf('Linux') !== -1) _OperatingSystem = OperatingSystems.Linux;
if (_UserAgent.indexOf('iPad') !== -1) _OperatingSystem = OperatingSystems.iOS;
if (_UserAgent.indexOf('iPhone') !== -1) _OperatingSystem = OperatingSystems.iOS;
if (_UserAgent.indexOf('iPod') !== -1) _OperatingSystem = OperatingSystems.iOS;
if (_UserAgent.toLowerCase().indexOf('android') !== -1) _OperatingSystem = OperatingSystems.Andriod;
if (_UserAgent.indexOf('Windows Phone') !== -1) _OperatingSystem = OperatingSystems.WindowsPhone;
const GetMonthPrecipitation = async (WeatherParameters) => {
const DateTime = luxon.DateTime;
const today = DateTime.local().startOf('day').toISO().replace('.000','');
@ -152,13 +83,6 @@ const GetMonthPrecipitation = async (WeatherParameters) => {
};
String.prototype.capitalize = function () {
return this.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
};
Date.prototype.stdTimezoneOffset = function () {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
@ -397,104 +321,6 @@ var canvasProgress_mousemove = function (e) {
}
}
};
var canvasProgress_click = function (e) {
var Hazards = _WeatherParameters.WeatherHazardConditions.Hazards;
var RatioX = canvasProgress.width() / 640;
var RatioY = canvasProgress.height() / 480;
if (e.offsetX >= (70 * RatioX) && e.offsetX <= (565 * RatioX)) {
if (e.offsetY >= (100 * RatioY) && e.offsetY < (129 * RatioY)) {
if (_WeatherParameters.Progress.CurrentConditions === LoadStatuses.Loaded) {
// Current Conditions
_CurrentCanvasType = CanvasTypes.CurrentWeather;
AssignPlayMsOffsets();
//window.location.hash = "#aCurrentWeather";
NavigateReset();
}
} else if (e.offsetY >= (129 * RatioY) && e.offsetY < (158 * RatioY)) {
// Latest Observations
if (_WeatherParameters.Progress.NearbyConditions === LoadStatuses.Loaded) {
_CurrentCanvasType = CanvasTypes.LatestObservations;
AssignPlayMsOffsets();
//window.location.hash = "#aLatestObservations";
NavigateReset();
}
} else if (e.offsetY >= (158 * RatioY) && e.offsetY < (187 * RatioY)) {
// Travel Forecast
if (_WeatherParameters.Progress.TravelForecast === LoadStatuses.Loaded) {
_CurrentCanvasType = CanvasTypes.TravelForecast;
UpdateTravelCities(0);
AssignPlayMsOffsets();
//window.location.hash = "#aTravelForecast";
NavigateReset();
}
} else if (e.offsetY >= (187 * RatioY) && e.offsetY < (216 * RatioY)) {
// Regional Forecast
if (_WeatherParameters.Progress.TomorrowsRegionalMap === LoadStatuses.Loaded) {
_CurrentCanvasType = CanvasTypes.RegionalForecast1;
//window.location.hash = "#aRegionalForecast";
AssignPlayMsOffsets();
NavigateReset();
}
} else if (e.offsetY >= (216 * RatioY) && e.offsetY < (245 * RatioY)) {
if (_WeatherParameters.Progress.CurrentRegionalMap === LoadStatuses.Loaded) {
// Regional Observations
_CurrentCanvasType = CanvasTypes.RegionalObservations;
AssignPlayMsOffsets();
//window.location.hash = "#aRegionalObservations";
NavigateReset();
}
} else if (e.offsetY >= (245 * RatioY) && e.offsetY < (274 * RatioY)) {
// Local Forecast
if (_WeatherParameters.Progress.WordedForecast === LoadStatuses.Loaded) {
_CurrentCanvasType = CanvasTypes.LocalForecast;
UpdateLocalForecast(0);
AssignPlayMsOffsets();
//window.location.hash = "#aLocalForecast";
NavigateReset();
}
} else if (e.offsetY >= (274 * RatioY) && e.offsetY < (303 * RatioY)) {
// Extended Forecast
if (_WeatherParameters.Progress.FourDayForecast === LoadStatuses.Loaded) {
_CurrentCanvasType = CanvasTypes.ExtendedForecast1;
AssignPlayMsOffsets();
//window.location.hash = "#aExtendedForecast";
NavigateReset();
}
} else if (e.offsetY >= (303 * RatioY) && e.offsetY < (332 * RatioY)) {
// Almanac
if (_WeatherParameters.Progress.Almanac === LoadStatuses.Loaded) {
_CurrentCanvasType = CanvasTypes.Almanac;
AssignPlayMsOffsets();
//window.location.hash = "#aAlmanac";
NavigateReset();
}
} else if (e.offsetY >= (332 * RatioY) && e.offsetY < (361 * RatioY)) {
// Local Radar
if (_WeatherParameters.Progress.DopplerRadar === LoadStatuses.Loaded) {
_CurrentCanvasType = CanvasTypes.LocalRadar;
UpdateDopplarRadarImage(0);
AssignPlayMsOffsets();
//window.location.hash = "#aLocalRadar";
NavigateReset();
}
} else if (e.offsetY >= (361 * RatioY) && e.offsetY < (390 * RatioY)) {
// Hazards
if (_WeatherParameters.Progress.Hazards === LoadStatuses.Loaded && Hazards.length > 0) {
_CurrentCanvasType = CanvasTypes.Hazards;
UpdateHazards(0);
AssignPlayMsOffsets();
//window.location.hash = "#aHazards";
NavigateReset();
}
}
}
};
var PopulateHazardConditions = function (WeatherParameters) {
if (WeatherParameters === null || (_DontLoadGifs && WeatherParameters.Progress.Hazards !== LoadStatuses.Loaded)) {
return;
@ -689,17 +515,6 @@ const WeatherMonthlyTotalsParser = (text) => {
return +text.match(/MONTH TO DATE\s*(\d{1,2}\.\d\d)/)[1];
};
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 1)) {
s = '0' + s;
}
return s;
};
const Progress = function (e) {