-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnumbeo-cost-of-living-comparison.user.js
290 lines (243 loc) · 8.4 KB
/
numbeo-cost-of-living-comparison.user.js
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// ==UserScript==
// @name numbeo-cost-of-living-comparison
// @namespace http://tampermonkey.net/
// @version 0.2.0
// @description Visualize cost-of-living data diff from numbeo.com
// @author neotan
// @match https://www.numbeo.com/*
// @grant GM_addStyle
// @grant GM_getResourceText
// @resource pureCss https://cdn.jsdelivr.net/npm/purecss@1.0.1/build/pure-min.min.css
// @resource tabulatorCss https://cdn.jsdelivr.net/npm/tabulator-tables@4.5.3/dist/css/tabulator.min.css
// @require https://cdn.jsdelivr.net/npm/echarts@4.6.0/dist/echarts.min.js
// @require https://cdn.jsdelivr.net/npm/tabulator-tables@4.5.3/dist/js/tabulator.min.js
// @require https://cdn.jsdelivr.net/npm/ramda@0.26.1/dist/ramda.min.js
// ==/UserScript==
;(async function() {
'use strict'
//------------------- Utilities START -------------------//
function renameKeys(cityName, rows) {
if (!rows) return
return R.map(
R.pipe(
R.toPairs,
R.map(([key, val]) => (['idx', 'item', 'category'].includes(key) ? [key, val] : [`${cityName}-${key}`, val])),
R.fromPairs
)
)(rows)
}
function camelize(str) {
if (!str) return str
return R.replace(/(?<=^|-)./g, R.toUpper)(str)
}
function toNumber(str) {
if (str == null) return
var numArr = str.trim().match(/[\d.-]/g)
return numArr == null ? numArr : parseFloat(numArr.join(''))
}
function scrollTo(htmlSelector) {
setTimeout(() => {
var scrollTop = $(htmlSelector).position().top || 0
$('html, body').animate({ scrollTop }, 'slow')
}, 3000)
}
function citiesStrToArray(citiesStr) {
if (!citiesStr) return
return R.pipe(R.split(','), R.map(R.pipe(R.trim, R.toLower, camelize)))(citiesStr)
}
function extractCostFromDoc(doc = '') {
var trs = $(doc).find('table.data_wide_table tr')
if (trs.length === 0) return
var category = 'Unknown'
return trs
.toArray()
.map((tr, idx) => {
var ths = $(tr).find('th')
var tds = $(tr).find('td')
var item
var median
var range
if (ths.length > 0) {
category = ths
.eq(0)
.text()
.trim()
} else if (tds.length > 0) {
item = tds
.eq(0)
.text()
.trim()
median = toNumber(
tds
.eq(1)
.text()
.trim()
)
range = tds
.eq(2)
.text()
.trim()
}
return item === null ? null : { idx, category, item, median, range }
})
.filter(row => row.item)
}
var cityCostUrl = 'https://www.numbeo.com/cost-of-living/in/'
async function fetchCityCostByName(cityName) {
try {
var response = await fetch(`${cityCostUrl}${cityName}`)
return response.text() // return a promise
} catch (err) {
console.warn(err)
}
}
function createSubColumns(data, showedSubColumnKeys = []) {
if (!data) return
return R.pipe(
R.mapObjIndexed((rows = [], cityName) => {
var columns = R.pipe(
R.prop(0),
R.pick(showedSubColumnKeys),
R.keys,
R.map(key => ({ title: key, field: `${cityName}-${key}`, sorter: 'number', align: 'right' }))
)(rows)
return {
title: cityName,
columns,
}
}),
R.values,
R.flatten
)(data)
}
var convertDataToRows = R.pipe(
R.mapObjIndexed((rows, cityName) => {
return renameKeys(cityName, rows)
}),
R.values,
R.reduce((acc, curr, i) => (acc == null ? curr : acc.map((obj, i) => R.mergeRight(obj, curr[i]))), null)
)
var barDefaultOptions = {
title: { text: 'Cost of Living' },
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
toolbox: { show: true, feature: { dataView: { title: 'View Data', readOnly: false }, restore: { title: 'Restore' } } },
calculable: true,
legend: {
align: 'right',
selector: [
{ type: 'all', title: 'All' },
{ type: 'inverse', title: 'Inverse' },
],
itemGap: 20,
},
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: { name: 'USD', type: 'value' },
yAxis: { type: 'category' },
dataZoom: [
{ show: true, top: '97%' },
{ show: true, yAxisIndex: 0, filterMode: 'none', width: 30, height: '80%', left: '95%', start: 80, end: 100 },
],
}
function getBarChartOption(cities = [], rows = [], options = {}) {
var sortedRows = R.pipe(
R.map(row => {
var sumMedian = R.pipe(
R.pickBy((_, key) => key.endsWith('-median')),
R.values,
R.sum
)(row)
return { ...row, sumMedian }
}),
R.sortBy(R.prop('sumMedian'))
)(rows)
var items = R.pluck('item')(sortedRows)
var series = R.map(city => {
var name = city
var data = R.pluck(`${city}-median`)(sortedRows)
return { name, data, type: 'bar' }
})(cities)
return R.pipe(R.assocPath(['legend', 'data'], cities), R.assocPath(['yAxis', 'data'], items), R.assoc('series', series))(options)
}
//------------------- Utilities END -------------------//
//------------------- Main Functions declaration START -------------------//
var defaultCities = 'irvine,seattle,los-angeles,austin,new-york,hoboken'
var defaultColumns
var showedSubColumnKeys
var domHtml
var costData
var barChart
function initEnv(cityNames) {
defaultColumns = [
{ title: 'Category', field: 'category' },
{ title: 'Item', field: 'item' },
]
showedSubColumnKeys = ['median']
domHtml = `
<form class="pure-form cities-form">
<label>
Cities: <input type="text" name="cities" size=100 placeholder="Input city names here." value=${cityNames.join(',')}>
</label>
<button type="submit" class="pure-button pure-button-primary" type="submit">Compare</button>
<span><a href="https://greasyfork.org/en/scripts/395215-numbeo-cost-of-living-comparison">☸</a></span>
</form>
<button class="pure-button pure-button-primary toggle-barchart">Toggle Bar-Chart</button>
<div id="echarts" style="width: 80%; height:700px;"/>
<button class="pure-button pure-button-primary toggle-table">Toggle Table</button>
<div id="tabulator-table" style="width: 80%;"/>
`
GM_addStyle(GM_getResourceText('pureCss'))
GM_addStyle(GM_getResourceText('tabulatorCss'))
$('body').prepend($(domHtml))
// initiate Charts
barChart = echarts.init(document.getElementById('echarts'))
barChart.showLoading({
text: 'Loading...',
})
// initiate listener
$('.toggle-barchart').click(() => $('#echarts').slideToggle('fast'))
$('.toggle-table').click(() => $('#tabulator-table').slideToggle('fast'))
$('.cities-form').submit(function(event) {
event.preventDefault()
var cityNames = R.pipe(() => $(this).serializeArray(), R.pathOr('', [0, 'value']), citiesStrToArray)(event)
if (cityNames) {
barChart.showLoading({
text: 'Loading...',
})
buildExtraDoms(cityNames)
return
}
})
console.log('init DONE!')
}
async function buildExtraDoms(cityNames) {
if (!cityNames || cityNames.length <= 0) return
try {
var promises = R.map(fetchCityCostByName)(cityNames)
var docs = await Promise.all(promises)
costData = R.pipe(R.zipObj(cityNames), R.map(extractCostFromDoc), R.reject(R.isNil))(docs)
var rows = convertDataToRows(costData)
// create Table
new Tabulator('#tabulator-table', {
// options ref: http://tabulator.info/examples/4.5
height: '500px',
movableColumns: true,
columns: [...defaultColumns, ...createSubColumns(costData, showedSubColumnKeys)],
data: convertDataToRows(costData),
})
// create Charts
var cities = R.keys(costData)
barChart.setOption(getBarChartOption(cities, rows, barDefaultOptions), true)
barChart.hideLoading()
scrollTo('.cities-form')
} catch (err) {
console.warn(err)
}
}
//------------------- Main Functions declaration END -------------------//
//------------------- Main Functions execution START -------------------//
var urlParams = new URLSearchParams(window.location.search)
var citiesStr = urlParams.get('cities')
var cityNames = citiesStrToArray(citiesStr || defaultCities)
initEnv(cityNames)
buildExtraDoms(cityNames)
})()