format-method.js 708 B

123456789101112131415161718192021222324252627
  1. "use strict";
  2. var isCallable = require("../object/is-callable")
  3. , value = require("../object/valid-value")
  4. , call = Function.prototype.call;
  5. module.exports = function (fmap) {
  6. fmap = Object(value(fmap));
  7. return function (pattern) {
  8. var context = this;
  9. value(context);
  10. pattern = String(pattern);
  11. return pattern.replace(/%([a-zA-Z]+)|\\([\u0000-\uffff])/g, function (
  12. match,
  13. token,
  14. escapeChar
  15. ) {
  16. var t, result;
  17. if (escapeChar) return escapeChar;
  18. t = token;
  19. while (t && !(result = fmap[t])) t = t.slice(0, -1);
  20. if (!result) return match;
  21. if (isCallable(result)) result = call.call(result, context);
  22. return result + token.slice(t.length);
  23. });
  24. };
  25. };