refactor: use scope variable memo for modern utils (#6954)

This commit is contained in:
Xin Du (Clark) 2020-02-09 11:44:54 +00:00 committed by GitHub
parent 6ae7718a42
commit 13cc924f02

View File

@ -1,3 +1,5 @@
import UAParser from 'ua-parser-js'
export const ModernBrowsers = { export const ModernBrowsers = {
Edge: '16', Edge: '16',
Firefox: '60', Firefox: '60',
@ -12,29 +14,36 @@ export const ModernBrowsers = {
'Mobile Safari': '10.3' 'Mobile Safari': '10.3'
} }
const modernBrowsers = new Proxy(ModernBrowsers, { let semver
get (browsers, prop) { let __modernBrowsers
if (browsers[prop] && !browsers[prop].version) {
const coerce = require('semver/functions/coerce') const getModernBrowsers = () => {
browsers[prop] = coerce(browsers[prop]) if (__modernBrowsers) {
return __modernBrowsers
} }
return browsers[prop]
__modernBrowsers = Object.keys(ModernBrowsers)
.reduce((allBrowsers, browser) => {
allBrowsers[browser] = semver.coerce(ModernBrowsers[browser])
return allBrowsers
}, {})
return __modernBrowsers
} }
})
export const isModernBrowser = (ua) => { export const isModernBrowser = (ua) => {
if (!ua) { if (!ua) {
return false return false
} }
const coerce = require('semver/functions/coerce') if (!semver) {
const gte = require('semver/functions/gte') semver = require('semver')
const UAParser = require('ua-parser-js') }
const { browser } = UAParser(ua) const { browser } = UAParser(ua)
const browserVersion = coerce(browser.version) const browserVersion = semver.coerce(browser.version)
if (!browserVersion) { if (!browserVersion) {
return false return false
} }
return Boolean(modernBrowsers[browser.name] && gte(browserVersion, modernBrowsers[browser.name])) const modernBrowsers = getModernBrowsers()
return Boolean(modernBrowsers[browser.name] && semver.gte(browserVersion, modernBrowsers[browser.name]))
} }
export const isModernRequest = (req, modernMode = false) => { export const isModernRequest = (req, modernMode = false) => {