From a8a19a04f796e32b79781c03c82286a310bcf5a4 Mon Sep 17 00:00:00 2001 From: kazuya kawaguchi Date: Fri, 12 Aug 2016 18:39:50 +0900 Subject: [PATCH] :chart_with_upwards_trend: performance(format): use hasOwn function of Vue.util --- src/extend.js | 3 ++- src/format.js | 58 ++++++++++++++++++++++++-------------------- test/specs/format.js | 5 +++- 3 files changed, 38 insertions(+), 28 deletions(-) diff --git a/src/extend.js b/src/extend.js index 17cb7999f..bb903cbb3 100644 --- a/src/extend.js +++ b/src/extend.js @@ -1,5 +1,5 @@ import { warn } from './util' -import format from './format' +import Format from './format' import { getValue } from './path' @@ -12,6 +12,7 @@ import { getValue } from './path' export default function (Vue) { const { isObject } = Vue.util + const format = Format(Vue) function parseArgs (...args) { let lang = Vue.config.lang diff --git a/src/format.js b/src/format.js index 4562478dd..6ff39cc9d 100644 --- a/src/format.js +++ b/src/format.js @@ -7,36 +7,42 @@ const RE_NARGS = /(%|)\{([0-9a-zA-Z_]+)\}/g -/** - * template - * - * @param {String} string - * @param {Array} ...args - * @return {String} - */ +export default function (Vue) { + const { hasOwn } = Vue.util + + /** + * template + * + * @param {String} string + * @param {Array} ...args + * @return {String} + */ + + function template (string, ...args) { + if (args.length === 1 && typeof args[0] === 'object') { + args = args[0] + } -export default function (string, ...args) { - if (args.length === 1 && typeof args[0] === 'object') { - args = args[0] - } + if (!args || !args.hasOwnProperty) { + args = {} + } - if (!args || !args.hasOwnProperty) { - args = {} - } + return string.replace(RE_NARGS, (match, prefix, i, index) => { + let result - return string.replace(RE_NARGS, (match, prefix, i, index) => { - let result + if (string[index - 1] === '{' + && string[index + match.length] === '}') { + return i + } else { + result = hasOwn(args, i) ? args[i] : null + if (result === null || result === undefined) { + return '' + } - if (string[index - 1] === '{' - && string[index + match.length] === '}') { - return i - } else { - result = args.hasOwnProperty(i) ? args[i] : null - if (result === null || result === undefined) { - return '' + return result } + }) + } - return result - } - }) + return template } diff --git a/test/specs/format.js b/test/specs/format.js index 07b4891cb..ae0afe3e9 100644 --- a/test/specs/format.js +++ b/test/specs/format.js @@ -1,5 +1,8 @@ +import Vue from 'vue' import assert from 'power-assert' -import format from '../../src/format' +import Format from '../../src/format' + +const format = Format(Vue) describe('format', () => {