Remedial Javascript (D. Crockford)


/ Published in: JavaScript
Save to your folder(s)

Remedial Javascript As Proposed by Douglas Crockford (http://javascript.crockford.com/remedial.html)


Copy this code and paste it in your HTML
  1. /*
  2.  Author: Douglas Crockford
  3.  Source: http://javascript.crockford.com
  4.  Description:
  5.  
  6.   Remedial Javascript As Proposed by Douglas Crockford (http://javascript.crockford.com/remedial.html)
  7.  
  8. */
  9.  
  10. var Remedial = (function(){
  11.  
  12. String.prototype.entityify = function () {
  13. return this.replace(/&/g, "&amp;").replace(/</g,
  14. "&lt;").replace(/>/g, "&gt;");
  15. };
  16.  
  17. String.prototype.quote = function () {
  18. var c, i, l = this.length, o = '"';
  19. for (i = 0; i < l; i += 1) {
  20. c = this.charAt(i);
  21. if (c >= ' ') {
  22. if (c === '\\' || c === '"') {
  23. o += '\\';
  24. }
  25. o += c;
  26. } else {
  27. switch (c) {
  28. case '\b':
  29. o += '\\b';
  30. break;
  31. case '\f':
  32. o += '\\f';
  33. break;
  34. case '\n':
  35. o += '\\n';
  36. break;
  37. case '\r':
  38. o += '\\r';
  39. break;
  40. case '\t':
  41. o += '\\t';
  42. break;
  43. default:
  44. c = c.charCodeAt();
  45. o += '\\u00' + Math.floor(c / 16).toString(16) +
  46. (c % 16).toString(16);
  47. }
  48. }
  49. }
  50. return o + '"';
  51. };
  52.  
  53. String.prototype.supplant = function (o) {
  54. return this.replace(/{([^{}]*)}/g,
  55. function (a, b) {
  56. var r = o[b];
  57. return typeof r === 'string' || typeof r === 'number' ? r : a;
  58. }
  59. );
  60. };
  61.  
  62. String.prototype.trim = function () {
  63. return this.replace(/^\s+|\s+$/g, "");
  64. };
  65.  
  66. // Do whatever you want here
  67. var R = {
  68. typeOf: function(value) {
  69. var s = typeof value;
  70. if (s === 'object') {
  71. if (value) {
  72. if (typeof value.length === 'number' &&
  73. !(value.propertyIsEnumerable('length')) &&
  74. typeof value.splice === 'function') {
  75. s = 'array';
  76. }
  77. } else {
  78. s = 'null';
  79. }
  80. }
  81. return s;
  82. },
  83. isEmpty: (o) {
  84. var i, v;
  85. if (typeOf(o) === 'object') {
  86. for (i in o) {
  87. v = o[i];
  88. if (v !== undefined && typeOf(v) !== 'function') {
  89. return false;
  90. }
  91. }
  92. }
  93. return true;
  94. }
  95.  
  96. }
  97. return R;
  98. })();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.