-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
258 lines (221 loc) · 8.17 KB
/
Copy pathutils.js
File metadata and controls
258 lines (221 loc) · 8.17 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Utils Module - Pure utility functions for formatting and common operations
// No dependencies on state - these are pure functions
const UtilsModule = (function() {
'use strict';
// ==================== CURRENCY FORMATTING ====================
/**
* Format currency based on display settings
* @param {number} value - The value to format
* @param {boolean} includeSign - Whether to include +/- sign
* @param {Object} displaySettings - Settings object with useCommas and useAbbreviated
* @returns {string} Formatted currency string
*/
function formatCurrency(value, includeSign = false, displaySettings = null) {
// Get settings from StateModule if not provided
const settings = displaySettings || (typeof StateModule !== 'undefined' ? StateModule.getDisplaySettings() : { useCommas: true, useAbbreviated: false });
const absValue = Math.abs(value);
const sign = includeSign ? (value >= 0 ? '+' : '-') : (value < 0 ? '-' : '');
const displayValue = absValue;
let formatted;
if (settings.useAbbreviated) {
if (displayValue >= 1000000) {
formatted = `${(displayValue / 1000000).toFixed(2)}M`;
} else if (displayValue >= 1000) {
formatted = `${(displayValue / 1000).toFixed(2)}K`;
} else {
formatted = displayValue.toFixed(2);
}
} else if (settings.useCommas) {
formatted = displayValue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
} else {
formatted = displayValue.toFixed(2);
}
return `${sign}$${formatted}`;
}
/**
* Format currency for chart display (simple format, always with commas)
* @param {number} value - The value to format
* @returns {string} Formatted currency string
*/
function formatCurrencySimple(value) {
return value.toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
/**
* Format a percentage value with sign
* @param {number} value - The percentage value
* @param {number} decimals - Number of decimal places
* @returns {string} Formatted percentage string
*/
function formatPercent(value, decimals = 2) {
if (value === null || value === undefined || isNaN(value)) return '--';
const sign = value >= 0 ? '+' : '';
return `${sign}${value.toFixed(decimals)}%`;
}
// ==================== DATE UTILITIES ====================
/**
* Get date from 7 days ago in YYYY-MM-DD format for X search
* @returns {string} Date string in YYYY-MM-DD format
*/
function getXSearchSinceDate() {
const now = new Date();
const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const year = weekAgo.getFullYear();
const month = String(weekAgo.getMonth() + 1).padStart(2, '0');
const day = String(weekAgo.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
/**
* Get human-readable date label (Today, Tomorrow, or formatted date)
* @param {number|string} timestamp - Date timestamp or string
* @returns {string} Human-readable date label
*/
function getDateLabel(timestamp) {
const date = new Date(timestamp);
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const eventDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
const diffDays = Math.round((eventDate - today) / (24 * 60 * 60 * 1000));
if (diffDays === 0) return 'Today';
if (diffDays === 1) return 'Tomorrow';
if (diffDays < 7) return date.toLocaleDateString('en-US', { weekday: 'long' });
return date.toLocaleDateString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric'
});
}
/**
* Get days until a given date
* @param {number|string} timestamp - Date timestamp or string
* @returns {number} Number of days until the date
*/
function getDaysUntil(timestamp) {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const eventDate = new Date(timestamp);
const eventDay = new Date(eventDate.getFullYear(), eventDate.getMonth(), eventDate.getDate());
return Math.round((eventDay - today) / (24 * 60 * 60 * 1000));
}
/**
* Format a timestamp for last updated display
* @param {number} timestamp - Timestamp in milliseconds
* @returns {string} Formatted time string
*/
function formatLastUpdated(timestamp) {
const date = new Date(timestamp);
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// ==================== NAME CLEANING ====================
/**
* Clean asset name for X search - removes pair suffixes for crypto and corporate suffixes for stocks
* @param {string} name - The asset name
* @param {string} ticker - The ticker symbol
* @returns {string} Cleaned name for search
*/
function cleanNameForXSearch(name, ticker) {
let cleanedName = name;
// Check if it's a crypto ticker (ends with -USD)
if (ticker && ticker.endsWith('-USD')) {
// Remove "USD" suffix from name (e.g., "Solana USD" -> "Solana")
cleanedName = cleanedName.replace(/\s+USD$/i, '');
} else {
// For stocks, remove common corporate suffixes
cleanedName = cleanedName
.replace(/,?\s*(Inc\.?|Incorporated|Corp\.?|Corporation|Ltd\.?|Limited|LLC|PLC|Co\.?|Company|Holdings?|Group|Technologies|International|Enterprises?|Solutions?|Services?|Systems?)(\s|$)+/gi, ' ')
.trim();
}
return cleanedName.trim();
}
// ==================== CASH UTILITIES ====================
/**
* Check if query matches cash keywords
* @param {string} query - The search query
* @returns {boolean} True if query is a cash keyword
*/
function isCashQuery(query) {
const CASH_KEYWORDS = (typeof ConfigModule !== 'undefined')
? ConfigModule.CASH_KEYWORDS
: ['cash', 'usd', 'dollars', 'dollar', '$'];
const lowerQuery = query.toLowerCase().trim();
return CASH_KEYWORDS.some(keyword => keyword === lowerQuery || lowerQuery.startsWith(keyword));
}
/**
* Get cash search result object
* @returns {Object} Cash search result
*/
function getCashSearchResult() {
const CASH_TICKER = (typeof ConfigModule !== 'undefined') ? ConfigModule.CASH_TICKER : 'CASH';
return {
symbol: CASH_TICKER,
name: 'US Dollars (Cash)',
type: 'CASH',
exchange: '',
isCash: true
};
}
// ==================== EVENT UTILITIES ====================
/**
* Get event icon name based on event type (returns Lucide icon name)
* @param {string} type - Event type
* @returns {string} Lucide icon name
*/
function getEventIcon(type) {
switch (type) {
case 'earnings': return 'calendar';
case 'dividend': return 'coins';
case 'ex-dividend': return 'alert-triangle';
case 'split': return 'scissors';
case 'economic_release': return 'bar-chart-3';
case 'fomc_decision': return 'landmark';
case 'fomc_minutes': return 'file-text';
default: return 'bell';
}
}
// ==================== ERROR DISPLAY ====================
/**
* Show error message to user
* @param {string} message - Error message to display
*/
function showError(message) {
const existingError = document.querySelector('.error-message');
if (existingError) {
existingError.remove();
}
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.textContent = message;
const addStockDiv = document.querySelector('.add-stock');
if (addStockDiv && addStockDiv.parentNode) {
addStockDiv.parentNode.insertBefore(errorDiv, addStockDiv.nextSibling);
}
setTimeout(() => {
errorDiv.remove();
}, 3000);
}
// ==================== PUBLIC API ====================
return {
// Currency formatting
formatCurrency,
formatCurrencySimple,
formatPercent,
// Date utilities
getXSearchSinceDate,
getDateLabel,
getDaysUntil,
formatLastUpdated,
// Name cleaning
cleanNameForXSearch,
// Cash utilities
isCashQuery,
getCashSearchResult,
// Event utilities
getEventIcon,
// Error display
showError
};
})();