Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

sprintf.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright 2011 Rackspace
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. var cache = {};
  18. // Do any others need escaping?
  19. var TO_ESCAPE = {
  20. '\'': '\\\'',
  21. '\n': '\\n'
  22. };
  23. function populate(formatter) {
  24. var i, type,
  25. key = formatter,
  26. prev = 0,
  27. arg = 1,
  28. builder = 'return \'';
  29. for (i = 0; i < formatter.length; i++) {
  30. if (formatter[i] === '%') {
  31. type = formatter[i + 1];
  32. switch (type) {
  33. case 's':
  34. builder += formatter.slice(prev, i) + '\' + arguments[' + arg + '] + \'';
  35. prev = i + 2;
  36. arg++;
  37. break;
  38. case 'j':
  39. builder += formatter.slice(prev, i) + '\' + JSON.stringify(arguments[' + arg + ']) + \'';
  40. prev = i + 2;
  41. arg++;
  42. break;
  43. case '%':
  44. builder += formatter.slice(prev, i + 1);
  45. prev = i + 2;
  46. i++;
  47. break;
  48. }
  49. } else if (TO_ESCAPE[formatter[i]]) {
  50. builder += formatter.slice(prev, i) + TO_ESCAPE[formatter[i]];
  51. prev = i + 1;
  52. }
  53. }
  54. builder += formatter.slice(prev) + '\';';
  55. cache[key] = new Function(builder);
  56. }
  57. /**
  58. * A fast version of sprintf(), which currently only supports the %s and %j.
  59. * This caches a formatting function for each format string that is used, so
  60. * you should only use this sprintf() will be called many times with a single
  61. * format string and a limited number of format strings will ever be used (in
  62. * general this means that format strings should be string literals).
  63. *
  64. * @param {String} formatter A format string.
  65. * @param {...String} var_args Values that will be formatted by %s and %j.
  66. * @return {String} The formatted output.
  67. */
  68. exports.sprintf = function(formatter, var_args) {
  69. if (!cache[formatter]) {
  70. populate(formatter);
  71. }
  72. return cache[formatter].apply(null, arguments);
  73. };