utils.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. * Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. * See COPYING.lesser and README.md in the root of this project for full details
  4. */
  5. var utils = {};
  6. /* return a vobject geometric attribute (i.e., position, etc.) value given its
  7. current and new values...
  8. oldVal newVal result
  9. aa;bbbb ccccc aa;cccc
  10. aa ccccc aa;cccc */
  11. utils.buildVobjGeomAttrVal =
  12. function(oldVal,newVal)
  13. {
  14. if( (matches = String(oldVal).match(/^(.*?)(;.*){0,1}$/)) )
  15. oldVal = matches[1];
  16. return oldVal+';'+newVal;
  17. };
  18. utils.clone =
  19. function(obj)
  20. {
  21. return (obj == undefined ? undefined : utils.jsonp(utils.jsons(obj)));
  22. };
  23. utils.contains =
  24. function(arr,x)
  25. {
  26. return arr.indexOf(x) > -1;
  27. };
  28. /* cause one type to inherit properties from another */
  29. utils.extend =
  30. function(child,parent)
  31. {
  32. for( var prop in parent.prototype )
  33. if( !(prop in child.prototype) )
  34. child.prototype[prop] = parent.prototype[prop];
  35. };
  36. /* remove specified elements from the array in-place, and return array */
  37. utils.filter =
  38. function(arr,items)
  39. {
  40. for( var i=0; i<arr.length; )
  41. if( utils.contains(items,arr[i]) )
  42. arr.splice(i,1);
  43. else
  44. i++;
  45. return arr;
  46. };
  47. /* flatten an array of arrays into a single array */
  48. utils.flatten =
  49. function(arrays)
  50. {
  51. return (arrays.length == 0 ?
  52. [] :
  53. [].concat.apply([], arrays));
  54. };
  55. /* return the given array's first element */
  56. utils.head =
  57. function(arr)
  58. {
  59. return arr[0];
  60. };
  61. utils.isArray =
  62. function(obj)
  63. {
  64. return Object.prototype.toString.call(obj) == '[object Array]';
  65. };
  66. utils.isObject =
  67. function(obj)
  68. {
  69. return Object.prototype.toString.call(obj) == '[object Object]';
  70. };
  71. /* increment the numeric part of a sequence# of the form 'src#number' */
  72. utils.incrementSequenceNumber =
  73. function(sn,inc)
  74. {
  75. var matches = sn.match(/(.*)#(\d*)/);
  76. return matches[1]+'#'+(parseInt(matches[2])+(inc == undefined ? 1 : inc));
  77. };
  78. utils.isHttpSuccessCode =
  79. function(statusCode)
  80. {
  81. return Math.floor(statusCode/100.0) == 2;
  82. };
  83. /* decode/encode a json string... in short, replace marked line breaks ('\\n')
  84. by placeholders so the source json string can be parsed... this enables
  85. multiline json values */
  86. utils.jsond =
  87. function(str,rep)
  88. {
  89. if( rep == undefined )
  90. rep = '\\\n';
  91. return str.replace(/\/\*newline\*\//g,rep);
  92. };
  93. utils.jsone =
  94. function(str)
  95. {
  96. return str.replace(/\\\n/g,'/*newline*/');
  97. };
  98. /* shortcuts for JSON.* functions */
  99. utils.jsonp =
  100. function(str)
  101. {
  102. return JSON.parse(str);
  103. };
  104. utils.jsons =
  105. function(obj,replacer,space)
  106. {
  107. return JSON.stringify(obj,replacer,space);
  108. };
  109. /* return an array containing all the keys of a hash */
  110. utils.keys =
  111. function(hash)
  112. {
  113. var keys = [];
  114. for( var k in hash )
  115. keys.push(k);
  116. return keys;
  117. };
  118. /* return the maximal value in an array given a measurement function */
  119. utils.max =
  120. function(arr,measure)
  121. {
  122. var max = -Infinity;
  123. arr.forEach(
  124. function(_)
  125. {
  126. var meas = measure(_);
  127. if( meas > max )
  128. max = meas;
  129. });
  130. return max;
  131. };
  132. /* merge an array of dictionaries into a single dictionary... in case of key
  133. clashes, the value in the furthest dictionary is taken */
  134. utils.mergeDicts =
  135. function(dicts)
  136. {
  137. if( dicts.length == 0 )
  138. return {};
  139. var merged = {};
  140. dicts.forEach(
  141. function(d)
  142. {
  143. for( var key in d )
  144. merged[key] = d[key];
  145. });
  146. return merged;
  147. };
  148. /* escapes regexp special characters from a string (so the string can be used as
  149. data within a regexp) */
  150. utils.regexpe =
  151. function(str)
  152. {
  153. return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  154. };
  155. /* return a dicts keys sorted by value according to the given function */
  156. utils.sortDict =
  157. function(dict,sortf)
  158. {
  159. var tuples = [];
  160. for(var key in dict)
  161. tuples.push([key, dict[key]]);
  162. tuples.sort( function(a,b) {return sortf(a[1],b[1]);} );
  163. return tuples.map( function(t) {return t[0];} );
  164. };
  165. /* remove specified keys from given dictionary (in-place) and return dictionary
  166. of removed entries */
  167. utils.splitDict =
  168. function(dict,keys)
  169. {
  170. var other = {};
  171. keys.forEach(
  172. function(k)
  173. {
  174. if( k in dict )
  175. {
  176. other[k] = dict[k];
  177. delete dict[k];
  178. }
  179. });
  180. return other;
  181. };
  182. /* returns the numeric part of a sequence# of the form 'src#number' */
  183. utils.sn2int =
  184. function(sn)
  185. {
  186. return parseInt(sn.match(/.*#(\d*)/)[1]);
  187. };
  188. /* return the given array's last element */
  189. utils.tail =
  190. function(arr)
  191. {
  192. return arr[arr.length-1];
  193. };
  194. /* transform the given array into a set (i.e., remove duplicate elements) */
  195. utils.toSet =
  196. function(arr)
  197. {
  198. var set = [];
  199. arr.forEach(
  200. function(_)
  201. {
  202. if( ! utils.contains(set,_) )
  203. set.push(_);
  204. });
  205. return set;
  206. };
  207. /* return an array containing all the values of a hash */
  208. utils.values =
  209. function(hash)
  210. {
  211. var values = [];
  212. for( var k in hash )
  213. values.push(hash[k]);
  214. return values;
  215. };
  216. /* creates a cookie with given name and value, which expires after the given
  217. amount of days (undefined == expire when browser closes) */
  218. utils.createCookie =
  219. function(name,value,days) {
  220. if (days) {
  221. var date = new Date();
  222. date.setTime(date.getTime()+(days*24*60*60*1000));
  223. var expires = "; expires="+date.toGMTString();
  224. }
  225. else var expires = "";
  226. document.cookie = name+"="+value+expires+"; path=/";
  227. };
  228. /* returns the value of the cookie with given name */
  229. utils.readCookie =
  230. function(name) {
  231. var nameEQ = name + "=";
  232. var ca = document.cookie.split(';');
  233. for(var i=0;i < ca.length;i++) {
  234. var c = ca[i];
  235. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  236. if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  237. }
  238. return null;
  239. };
  240. /* erases the cookie with given name */
  241. utils.eraseCookie =
  242. function(name) {
  243. createCookie(name,"",-1);
  244. };
  245. __pendingCalls = {};
  246. /* performs a function after the specified amount of milleseconds
  247. unless this call is repeated during that time interval. If it is,
  248. the timer is reset. 'args' is an array containing arguments for the
  249. function call. */
  250. utils.doAfterUnlessRepeated =
  251. function(func, args, ms) {
  252. function doIt() {
  253. func.apply(undefined, args);
  254. }
  255. if (__pendingCalls[func]) {
  256. clearTimeout(__pendingCalls[func]);
  257. }
  258. __pendingCalls[func] = setTimeout(doIt, ms);
  259. };
  260. /* NOTE: 'exports' exists in back-end 'require', but not in browser import...
  261. this ensures no errors are reported during browser imports */
  262. var exports = exports || {};
  263. exports.buildVobjGeomAttrVal = utils.buildVobjGeomAttrVal;
  264. exports.clone = utils.clone;
  265. exports.contains = utils.contains;
  266. exports.extend = utils.extend;
  267. exports.filter = utils.filter;
  268. exports.flatten = utils.flatten;
  269. exports.head = utils.head;
  270. exports.isArray = utils.isArray;
  271. exports.isObject = utils.isObject;
  272. exports.incrementSequenceNumber = utils.incrementSequenceNumber;
  273. exports.isHttpSuccessCode = utils.isHttpSuccessCode;
  274. exports.jsond = utils.jsond;
  275. exports.jsone = utils.jsone;
  276. exports.jsonp = utils.jsonp;
  277. exports.jsons = utils.jsons;
  278. exports.keys = utils.keys;
  279. exports.max = utils.max;
  280. exports.mergeDicts = utils.mergeDicts;
  281. exports.regexpe = utils.regexpe;
  282. exports.sortDict = utils.sortDict;
  283. exports.splitDict = utils.splitDict;
  284. exports.sn2int = utils.sn2int;
  285. exports.tail = utils.tail;
  286. exports.toSet = utils.toSet;
  287. exports.values = utils.values;
  288. exports.createCookie = utils.createCookie;
  289. exports.readCookie = utils.readCookie;
  290. exports.eraseCookie = utils.eraseCookie;
  291. exports.doAfterUnlessRepeated = utils.doAfterUnlessRepeated;