utils.js 8.3 KB

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