useful.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /* appjet:version 0.1 */
  2. /* appjet:library */
  3. // Copyright (c) 2009, Herbert Vojčík
  4. // Licensed by MIT license (http://www.opensource.org/licenses/mit-license.php)
  5. /**@overview This library contains various utility functions
  6. * that appeared during developing other apps but are general enough.
  7. */
  8. /**
  9. * Returns global object.
  10. */
  11. function global() { return {}.valueOf.call(); }
  12. /**
  13. * Read-only wrapper on an object.
  14. */
  15. function readonly(o) {
  16. return appjet._native.createProxyObject(
  17. function(name) { return o[name]; },
  18. function() {},
  19. function() {},
  20. function() { return []; },
  21. o
  22. );
  23. }
  24. /**
  25. * Extends an object by copying all other object's own properties.
  26. * Returns the extended object. This implies you can create clone
  27. * of simple object by extend({}, x).
  28. */
  29. function extend(dst, src) {
  30. eachProperty(src, function(p) { dst[p] = src[p]; });
  31. return dst;
  32. }
  33. /**
  34. * Akin to <code>Array >> streamContents:</code> in Smalltalk.
  35. * Calls f and returns array of every item that was printed using print.
  36. * Useful for collecting any item in some loop(s) for which
  37. * filter or map can not be straightforwardly used. Both examples get keys
  38. * of own properties
  39. @example
  40. collectPrint(function() { eachProperty(object, print); });
  41. collectPrint(function() {for (var p in object) { if (object.hasOwnProperty(p) print(p); }});
  42. */
  43. function collectPrint(f) {
  44. var result = [];
  45. var _g = global();
  46. var savedPrint = _g.print;
  47. _g.print = function() { result.push.apply(result, arguments); }; // cannot inline, or f***ing try/finally bug which nobody is willing to fix appears
  48. try { f(); } finally { _g.print = savedPrint; }
  49. return result;
  50. }
  51. function _collector(result) { return function() { result.push.apply(result, arguments); }; }
  52. /**
  53. * Akin to <code>Array >> streamContents:</code> in Smalltalk.
  54. * Calls f and returns array of every item that was yielded using yield.
  55. * Useful for collecting any item in some loop(s) for which
  56. * filter or map can not be straightforwardly used. An example gets keys
  57. * of own properties
  58. @example
  59. collectYield(function () {for (var p in object) { if (object.hasOwnProperty(p) yield p; }});
  60. */
  61. function collectYield(f) {
  62. var result = [];
  63. var gen = f();
  64. try {
  65. for(;;) { result.push(gen.next()); }
  66. } catch (ex if ex instanceof StopIteration) {
  67. //gen.close(); //strange, not needed
  68. }
  69. return result;
  70. }
  71. //from web; then edited
  72. /** Converts h,s,v (0-1) to rgb (0-255). Returns array [r, g, b]. */
  73. function hsv2rgb(h,s,v) {
  74. // Adapted from http://www.easyrgb.com/math.html
  75. // hsv values = 0 - 1, rgb values = 0 - 255
  76. var r, g, b;
  77. if (s == 0) {
  78. r = g = b = v;
  79. } else {
  80. var vh = 6*h;
  81. var vi = Math.floor(vh);
  82. var v1 = v*(1-s);
  83. var v2 = v*(1-s*(vh-vi));
  84. var v3 = v*(1-s*(1-(vh-vi)));
  85. switch(vi) {
  86. case 0: r = v; g = v3; b = v1; break;
  87. case 1: r = v2; g = v; b = v1; break;
  88. case 2: r = v1; g = v; b = v3; break;
  89. case 3: r = v1; g = v2; b = v; break;
  90. case 4: r = v3; g = v1; b = v; break;
  91. case 5: r = v; g = v1; b = v2; break;
  92. }
  93. }
  94. return [ Math.round(255*r), Math.round(255*g), Math.round(255*b) ];
  95. }
  96. /**
  97. * Call this function with etag of actual requested resource.
  98. * Includes caching headers in the response,
  99. * and if the ETag matches, it immediately stops the response
  100. * with "304 Not Modified"; in other case it returns
  101. * and lets you continue with populating the response data.
  102. * Call after you KNOW the resource exists! It is illegal
  103. * to change response status to 404 or similar after this call.
  104. */
  105. function etagCaching(etag) {
  106. response.setCacheable(null);
  107. response.setHeader("Cache-Control", "public, must-revalidate");
  108. response.setHeader("ETag", etag);
  109. var cond = request.headers["If-None-Match"];
  110. if (cond && (cond === "*" || ([].concat(cond).indexOf(etag) !== -1))) {
  111. response.setStatusCode(304);
  112. response.stop();
  113. }
  114. }
  115. /**
  116. * Splits all elements of an array by delimiter
  117. * and insert o in places where split occurred.
  118. * Returns modified array with split parts and delimiting o's.
  119. */
  120. function splitReplace(array, delimiter, o) {
  121. var i, j, k, l = 0, m = array.length;
  122. array.forEach(function (v, k, a) {
  123. var split = a[k] = v.split ? v.split(delimiter) : [v];
  124. l += 2 * split.length - 1;
  125. });
  126. array.length = l;
  127. for (var i = m-1, j = l-1; i >= 0; i--) {
  128. var parts = array[i];
  129. for (var k = parts.length - 1; k > 0; --k) {
  130. array[j--] = parts[k--];
  131. array[j--] = o;
  132. }
  133. array[j--] = parts[0];
  134. }
  135. return array;
  136. }
  137. /* appjet:server */
  138. import("lib-support/jsunit");
  139. var _l = import({}, "lib-support/useful");
  140. // ==== Test cases ====
  141. page.testSuite = [
  142. function collectPrintCollectsPrintedArguments() {
  143. var collected = _l.collectPrint(function() {
  144. print("Hello", "world", "!");
  145. print();
  146. print(3,1,4);
  147. });
  148. assertArrayEquals("Incorrect items collected.", ["Hello", "world", "!", 3, 1, 4], collected);
  149. },
  150. function collectPrintRetainsLegacyPrint() {
  151. var savedPrint = this.print;
  152. _l.collectPrint(function() {
  153. print("Hello", "world", "!");
  154. print();
  155. print(3,1,4);
  156. });
  157. assertEquals("Print not retained.", savedPrint, this.print);
  158. },
  159. function collectPrintRetainsLegacyPrintInCaseOfException() {
  160. var savedPrint = this.print;
  161. var f = function() { throw "exception"; };
  162. try {
  163. _l.collectPrint(f);
  164. fail("Exception not thrown");
  165. } catch(ex if ex === "exception") {
  166. // pass
  167. }
  168. assertEquals("Print not retained.", savedPrint, this.print);
  169. },
  170. function collectPrintRetainsLegacyPrintInCaseOfUndefinedException() {
  171. var savedPrint = this.print;
  172. var f = function() { throw undefined; };
  173. try {
  174. _l.collectPrint(f);
  175. fail("Exception not thrown");
  176. } catch(ex if ex === undefined) {
  177. // pass
  178. }
  179. assertEquals("Print not retained.", savedPrint, this.print);
  180. },
  181. function collectYieldCollectsYieldedArguments() {
  182. var collected = _l.collectYield(function() {
  183. yield "Hello";
  184. yield 3;
  185. });
  186. assertArrayEquals("Incorrect items collected.", ["Hello", 3], collected);
  187. },
  188. function collectYieldCollectsYieldeesFromTryBlockAndFinallyRuns() {
  189. var frun = false;
  190. var collected = _l.collectYield(function() {
  191. try {
  192. yield "Hello";
  193. yield 3;
  194. } finally { frun = true; }
  195. });
  196. assertArrayEquals("Incorrect items collected.", ["Hello", 3], collected);
  197. assertTrue("Finally did not run", frun);
  198. },
  199. function collectYieldThrowsExceptionIfThrownInF() {
  200. try {
  201. var collected = _l.collectYield(function() {
  202. yield "Hello";
  203. throw "exception";
  204. yield "world";
  205. });
  206. fail("Exception not thrown.");
  207. } catch(ex if ex === "exception") {
  208. // pass
  209. }
  210. },
  211. function collectYieldThrowsUndefinedIfThrownInF() {
  212. try {
  213. var collected = _l.collectYield(function() {
  214. yield "Hello";
  215. throw undefined;
  216. yield "world";
  217. });
  218. fail("Exception not thrown.");
  219. } catch(ex if ex === undefined) {
  220. // pass
  221. }
  222. },
  223. function collectYieldThrowsExceptionIfExceptionThrownInF_AndFinallyInFRuns() {
  224. var finallyRun = false;
  225. try {
  226. var collected = _l.collectYield(function() {
  227. try {
  228. yield "Hello";
  229. throw "exception";
  230. yield "world";
  231. } finally { finallyRun = true; }
  232. });
  233. fail("Exception not thrown.");
  234. } catch(ex if ex === "exception") {
  235. // pass
  236. }
  237. assertTrue("Finally in f did not run.", finallyRun);
  238. },
  239. function readonlyReadsCorrectlyAndIsDynamic() {
  240. var x = {hello: "world"};
  241. var rx = _l.readonly(x);
  242. assertEquals("Hello read incorrectly", "world", rx.hello);
  243. assertUndefined("Nonexistent property is not undefined", rx.thisIsNot);
  244. x.hello = "again";
  245. x.thisIsNot = "this is";
  246. assertEquals("Hello read incorrectly", "again", rx.hello);
  247. assertEquals("ThisIsNot read incorrectly", "this is", rx.thisIsNot);
  248. },
  249. function readonlyIsReadOnly() {
  250. var x = {hello: "world"};
  251. var rx = _l.readonly(x);
  252. rx.thisIsNot = "this is";
  253. delete rx.hello;
  254. assertEquals("Hello read incorrectly", "world", rx.hello);
  255. assertUndefined("Nonexistent property is not undefined", rx.thisIsNot);
  256. },
  257. function extendExtendsCorrectlyForAllCombinations() {
  258. var srcProto = { pro: "to" }
  259. var src = object(srcProto);
  260. src.a = "b"; src.c = "d";
  261. var dst = { pro: "fi", a: "bc", yes: "true" };
  262. var result = _l.extend(dst, src);
  263. assertEquals("extend did not return extended object", dst, result);
  264. assertEquals("a wasn't copied", "b", dst.a);
  265. assertEquals("c wasn't copied", "d", dst.c);
  266. assertEquals("pro was changed", "fi", dst.pro);
  267. assertEquals("yes was changed", "true", dst.yes);
  268. },
  269. //TODO tests for splitReplace
  270. ];
  271. // ==== Test runner ====
  272. import("lib-support/runner");
  273. runTestsByDefault();