Posted By

icoder on 09/04/09


Tagged

library base


Versions (?)

jsCore


 / Published in: JavaScript
 

URL: http://icoder.dk

This i my base library with extensions to the JavaScript objects like String and Date

  1. // Udviddelser af Javascript objekterne. Generel funktionalitet og formatering
  2. var Globals = function() {
  3. var _jsonDateExp = /\/Date\((\d+)\)\//;
  4. var _bindingExp = /\{([^\}\:]+)(\:[^\}]+)?\}/g;
  5. var _idxBindingExp = /\{(\d)(\:[^\}]+)?\}/g;
  6.  
  7. var _monthNames = ["januar", "februar", "marts", "april", "maj", "juni", "juli", "august", "september", "oktober", "november", "december"];
  8. var _dayNames = ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"];
  9. return {
  10. jsonDateExp: function() { return _jsonDateExp; },
  11. bindingExp: function() { return _bindingExp; },
  12. idxBindingExp: function() { return _idxBindingExp; },
  13. monthNames: function() { return _monthNames; },
  14. dayNames: function() { return _dayNames; }
  15. }
  16. } ();
  17.  
  18. String.prototype.format = function() {
  19. ///<SUMMARY>Bruger strengen som bindingsudtryk, og indsætter argumenterne på de angivne pladser.
  20. ///Eks.: "Say: {0}".format("Hello World")</SUMMARY>
  21. /// <PARAM name="args" />Op til 10 objekter der skal indsættes i formateringsstrengen</PARAM>
  22. /// <RETURNS type="String" />
  23. var re = Globals.idxBindingExp();
  24. var params = arguments;
  25. var builder = this.replace(re, function() {
  26. if (arguments[1] >= params.length)
  27. throw new Error("String.format: Bindingsudtryk stemmer ikke over ens med antal af argumenter");
  28. var format = arguments[2] ? arguments[2].slice(1) : "";
  29. return format ? params[arguments[1]].format(format) : params[arguments[1]];
  30. });
  31. return builder;
  32. };
  33.  
  34. String.prototype.bind = function(item) {
  35. var re = Globals.bindingExp();
  36. var dateRe = Globals.jsonDateExp();
  37.  
  38. return this.replace(re, function() {
  39. if (typeof (item[arguments[1]]) == "undefined")
  40. throw new Error("String.bind: Ukendt bindingsudtryk: " + arguments[1]);
  41. var format = arguments[2] ? arguments[2].slice(1) : null;
  42. var key = arguments[1];
  43.  
  44. if (dateRe.test(item[key]))
  45. item[key] = eval(item[key].replace(dateRe, "new Date($1)"));
  46. return format ? item[key].format(format) : item[key];
  47. });
  48. };
  49.  
  50. String.prototype.repeat = function(n) {
  51. ///<SUMMARY>Gentager en given streng n gange</SUMMARY>
  52. return new Array(n + 1).join(this);
  53. };
  54.  
  55. String.prototype.capitalize = function() {
  56. /// <SUMMARY>Sætter begyndelsesbogstaver i strengen til store bogstaver.</SUMMARY>
  57. var re = /\b(\w)([\wæøå]*)\b/g;
  58. return this.replace(re, function() {
  59. if (arguments.length > 2)
  60. return arguments[1].toUpperCase() + arguments[2];
  61. return null;
  62. });
  63. };
  64.  
  65. String.prototype.compare = function(str) {
  66. ///<SUMMARY>Sammenligner med streng, og returnerer sortering alfabetisk</SUMMARY>
  67. if (this == str)
  68. return 0;
  69. var arr = [this, str];
  70. arr.sort();
  71. return arr[0] == this ? -1 : 1;
  72. };
  73.  
  74. Number.prototype.fix = function(n) {
  75. /// <SUMMARY>Returnerer tallet med foranstillede nuller</SUMMARY>
  76. /// <PARAM name="n" type="Integer" />Antal karakterer der skla returneres</PARAM>
  77. /// <RETURNS type="String" />
  78. var number = this.toString();
  79. if (number.length > n)
  80. return number;
  81.  
  82. var builder = "0".repeat(n);
  83. builder = builder.slice(0, builder.length - number.length) + number;
  84. return builder;
  85. };
  86.  
  87. Date.prototype.format = function(formatString) {
  88. /// <SUMMARY>Formaterer datoer i henhold til det angivne format</SUMMARY>
  89. /// <PARAM type="String" />F.eks.: d. MMM yy hh:mm eller: dd/MM-yyyy</PARAM>
  90. /// <RETURNS type="String" />
  91. var monthNames = Globals.monthNames();
  92. var builder = formatString;
  93.  
  94. if (m = formatString.match(/^j$/i))
  95. return "\\/Date({0})\\/".format(this.getTime());
  96.  
  97. if (m = formatString.match(/d{1,2}/)) {
  98. if (m[0].length == 1)
  99. builder = builder.replace(m[0], this.getDate());
  100. else
  101. builder = builder.replace(m[0], this.getDate().fix(2));
  102. }
  103. if (m = formatString.match(/M{1,3}/)) {
  104. var str = m[0].length < 3 ? (this.getMonth() + 1).fix(m[0].length) : monthNames[this.getMonth()];
  105. builder = builder.replace(m[0], str);
  106. }
  107. if (m = formatString.match(/y{2,4}/)) {
  108. var str = m[0].length == 2 ? this.getFullYear().toString().slice(2, 4) : this.getFullYear().fix(m[0].length);
  109. builder = builder.replace(m[0], str);
  110. }
  111. if (m = formatString.match(/h{1,2}/)) {
  112. builder = builder.replace(m[0], this.getHours().fix(m[0].length));
  113. }
  114. if (m = formatString.match(/m{1,2}/)) {
  115. builder = builder.replace(m[0], this.getMinutes().fix(m[0].length));
  116. }
  117. if (m = formatString.match(/s{1,2}/)) {
  118. builder = builder.replace(m[0], this.getSeconds().fix(m[0].length));
  119. }
  120. return builder;
  121. };
  122.  
  123. Date.parseJson = function(json) {
  124. ///<summary>Statisk metode på Date - parser json datoer</summary>
  125. var re = /\\\/Date(\d+)\\\//;
  126. var code = json.replace(re, "new Date($1)");
  127. if (code != this)
  128. throw new Error("Ikke en Json dato: " + json);
  129. return eval(code);
  130. };
  131.  
  132. Date.prototype.isPast = function() {
  133. return (new Date()) > this;
  134. };
  135.  
  136. Date.prototype.getDayName = function() {
  137. return Globals.dayNames()[this.getDay()];
  138. };
  139.  
  140. Date.prototype.isToday = function() {
  141. var today = new Date();
  142. return this.getFullYear() == today.getFullYear() && this.getMonth() == today.getMonth() && this.getDate() == today.getDate();
  143. }
  144.  
  145. Date.prototype.getWeek = function() {
  146. var date = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
  147. var IsoDayOfWeek = date.getDay() == 0 ? 7 : date.getDay(); // Søndag = 7
  148. date.setDate(date.getDate() + 4 - IsoDayOfWeek); // Ændre til nærmeste torsdag
  149. var DayOfYear = (date.getTime() - Date.UTC(date.getFullYear(), 0, 1)) / 864e5;
  150. var week = Math.floor(DayOfYear / 7) + 1;
  151. return week;
  152. };
  153.  
  154. Date.prototype.addDays = function(days) {
  155. var result = new Date(this.getTime() + (1000 * 60 * 60 * 24 * days));
  156. var dst = result.getHours() - this.getHours();
  157. if (dst)
  158. result = new Date(this.getTime() + (1000 * 60 * 60 * (24 + dst) * days));
  159. return result;
  160. };
  161.  
  162. Date.prototype.addMonth = function(months) {
  163. var result = new Date(this);
  164. result.setMonth(this.getMonth() + months);
  165. return result;
  166. };
  167.  
  168. Array.prototype.each = function(handler) {
  169. /// <SUMMARY>Iterator funktion, der kalder handleren for hvert element i arrayen: handler(item, idx)</SUMMARY>
  170. for (var i = 0; i < this.length; i++)
  171. handler(this[i], i);
  172. };
  173.  
  174. Array.prototype.where = function(predicate) {
  175. var predicateFunction;
  176.  
  177. if (typeof predicate == "string") {
  178. predicateFunction = function(itm) {
  179. with (itm) {
  180. return eval(predicate);
  181. }
  182. };
  183. }
  184. else {
  185. predicateFunction = predicate;
  186. }
  187.  
  188. var result = [];
  189. this.each(function(itm, i) {
  190. if (predicateFunction(itm))
  191. result.push(itm);
  192. });
  193. return result;
  194. };
  195.  
  196. Array.prototype.limit = function(start, size) {
  197. return this.slice(start, start + size);
  198. }
  199.  
  200. Array.prototype.select = function(clause) {
  201. var result = [];
  202. if (typeof clause == "string") {
  203. for (var i = 0; i < this.length; i++)
  204. result.push(eval(clause));
  205. }
  206. else {
  207. for (var i = 0; i < this.length; i++)
  208. result.push(clause(this[i]));
  209. }
  210. return result;
  211. };
  212.  
  213. Array.prototype.orderBy = function(expression, direction) {
  214. ///<SUMMARY>Sorterer elementerne i henhold til expression udtrykket
  215. /// Hvis expression er en streng, forudsættes det at den er en property på alle elementer i array'et
  216. /// Hvis expression er en funktion, får den to array-elementer ind, og og forventes at returnerer -1, 0, 1.</SUMMARY>
  217. if (typeof direction != "string" || !/^(desc|asc)$/i.test(direction))
  218. throw new Error("Array.orderBy: direction argument, kan kun have værdien ASC eller DESC");
  219. var sortFunction;
  220. if (typeof expression == "string") {
  221. sortFunction = function(a, b) {
  222. var i = a[expression] - b[expression];
  223. if (isNaN(i)) {
  224. i = a[expression].compare(b[expression]);
  225. }
  226. return i;
  227. }
  228. }
  229. else {
  230. sortFunction = expression;
  231. }
  232. var result = this.clone();
  233. result.sort(sortFunction);
  234. if ((/desc/i).test(direction))
  235. result.reverse();
  236. return result;
  237. };
  238.  
  239. Array.prototype.clone = function() {
  240. var clone = [];
  241. this.each(function(itm) { clone.push(itm); });
  242. return clone;
  243. };
  244.  
  245. Array.prototype.render = function(template, renderCallback) {
  246. /// <SUMMARY>Udskriver alle elementer i følge skabelonen</SUMMARY>
  247. /// <PARAM name="template" type="string" />Streng med bindingssyntaks: Klammer med propertynavne. F.eks. Navn: {name}</PARAM>
  248. ///<PARAM name="renderCallback" />funktion der modtager resultatet af renderingen. funk(rowString, rowIdx)</PARAM>
  249. var result = [];
  250. var handler = (typeof renderCallback == "undefined") ?
  251. function(item) { result.push(template.bind(item)); } :
  252. function(item, idx) {
  253. var str = template.bind(item);
  254. result.push(str);
  255. renderCallback(str, idx);
  256. };
  257. this.each(handler);
  258. return result;
  259. };

Report this snippet  

You need to login to post a comment.