Vue Camelize函数缓存

271 阅读1分钟
function cached (fn) {
  /**
  * var cache = {};
        Creates an object that inherits the properties and methods from Object,such as toString(),etc...
    var cache  = Object.create(null);
        Creates an object that doesn't inherit anything.
  */
  var cache = Object.create(null);
  
  return (function cachedFn (str) {
    var hit = cache[str];
    console.log('hit',hit)
    return hit || (cache[str] = fn(str))
  })
}
var camelizeRE = /-(\w)/g
var camelize = cached(function (str) {
  return str.replace(camelizeRE, function (matchStr, replaceStr, indexOfSource, sourceStr) {
    return replaceStr ? replaceStr.toUpperCase() : ''
  })
})
camelize('H1-H2-H3')
camelize('H1-H2-H3')