helper.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. function get(url) {
  2. return new Promise(function(resolve, reject) {
  3. var req = new XMLHttpRequest();
  4. req.open('GET', url);
  5. req.onload = function() {
  6. if (req.status == 200) {
  7. resolve(req.response);
  8. }
  9. else {
  10. reject(Error(req.statusText));
  11. }
  12. };
  13. req.onerror = function() {
  14. reject(Error("Network Error"));
  15. };
  16. req.send();
  17. });
  18. }
  19. function getJSON(url) {
  20. return get(url).then(JSON.parse)
  21. }
  22. function sortByKey(key, d) {
  23. return d.slice().sort( function (a, b) {
  24. return a[key] - b[key]
  25. }).reverse()
  26. }
  27. function limit(key, m, d) {
  28. return d.filter( function (d) {
  29. return d[key].isAfter(m)
  30. })
  31. }
  32. function sum(a) {
  33. return a.reduce( function (a, b) {
  34. return a + b
  35. }, 0)
  36. }
  37. function one() {
  38. return 1
  39. }
  40. function trueDefault(d) {
  41. return d === undefined ? true : d
  42. }
  43. function dictGet(dict, key) {
  44. var k = key.shift()
  45. if (!(k in dict))
  46. return null
  47. if (key.length == 0)
  48. return dict[k]
  49. return dictGet(dict[k], key)
  50. }
  51. function localStorageTest() {
  52. var test = 'test'
  53. try {
  54. localStorage.setItem(test, test)
  55. localStorage.removeItem(test)
  56. return true
  57. } catch(e) {
  58. return false
  59. }
  60. }
  61. /* Helpers working with nodes */
  62. function offline(d) {
  63. return !d.flags.online
  64. }
  65. function online(d) {
  66. return d.flags.online
  67. }
  68. function has_location(d) {
  69. return "location" in d.nodeinfo
  70. }
  71. function subtract(a, b) {
  72. var ids = {}
  73. b.forEach( function (d) {
  74. ids[d.nodeinfo.node_id] = true
  75. })
  76. return a.filter( function (d) {
  77. return !(d.nodeinfo.node_id in ids)
  78. })
  79. }
  80. /* Helpers working with links */
  81. function showDistance(d) {
  82. if (isNaN(d.distance))
  83. return
  84. return numeral(d.distance).format("0,0") + " m"
  85. }
  86. function showTq(d) {
  87. return numeral(1/d.tq).format("0%")
  88. }
  89. /* Infobox stuff (XXX: move to module) */
  90. function attributeEntry(el, label, value) {
  91. if (value === null || value == undefined)
  92. return
  93. var tr = document.createElement("tr")
  94. var th = document.createElement("th")
  95. th.textContent = label
  96. tr.appendChild(th)
  97. var td = document.createElement("td")
  98. if (typeof value == "function")
  99. value(td)
  100. else
  101. td.appendChild(document.createTextNode(value))
  102. tr.appendChild(td)
  103. el.appendChild(tr)
  104. return td
  105. }