Skip to content

Instantly share code, notes, and snippets.

@Jokcy
Last active November 27, 2018 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jokcy/b51271ce2bd737d587c6e85da502f7a8 to your computer and use it in GitHub Desktop.
Save Jokcy/b51271ce2bd737d587c6e85da502f7a8 to your computer and use it in GitHub Desktop.
面试题1
const listeners = {}
// 不是很理解第三条。。。
const bus = {
on(event, fun) {
let handler
let before
if (typeof fun === 'object' && fun.fn) {
handler = fun.fn
before = fun.before
} else {
handler = fun
}
let realHandler
const promise = new Promise((resolve, reject) => {
realHandler = (...args) => {
// 如何确定`handler`是否执行完?
handler(...args)
}
})
before = Array.isArray(before) ? before : [before]
if (listeners[event]) {
if (before) {
let index = -1
let i
for (let i = 0; i<before.length; i++) {
i = listeners[event].indexOf(before(i))
if (i > index) {
index = i
}
}
if (index === -1) {
// throw error?
}
listeners[event].splice(index, 0, realHandler)
} else {
listeners[event].push(realHandler)
}
}
return promise
},
trigger(event, ...args) {
const eListeners = listeners[event]
// 检查
eListeners.forEach((listener) => listener(...args))
},
}
function parse(str) {
let type
let fields
let attrs
let relations = []
let typeSplit = str.split('{')
let typeWithAttrs = typeSplit[0]
// type and attrs
if (typeWithAttrs.indexOf('(') !== -1) {
let typeAttrSplit = typeWithAttrs.split('(')
type = typeAttrSplit[0]
attrs = typeAttrSplit[1].substr(0, typeAttrSplit[1] - 2) // 去掉后面的)
arrts = attrs.split(',')
attrs = attrs.reduce((result, attr) => {
let [key, value] = attr.split(':')
result[key] = value
}, {})
} else {
type = typeWithAttrs
}
fields = typeSplit[1].substr(0, typeSplit[1].length - 2) // 去掉}
// 这里还要处理`relation`里面的`,`
fields = fields.split(',')
fields = fields.reduce((result, field) => {
if (field.indexOf('{') === -1) {
result.push(field)
} else {
relations.push(field)
}
}, [])
return {
type,
fields,
attrs,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment