1
0
mirror of https://github.com/twbs/bootstrap.git synced 2025-09-02 18:02:37 +02:00

refactor: use a Map instead of an Object in dom/data (#32180)

Co-authored-by: XhmikosR <xhmikosr@gmail.com>
Co-authored-by: Rohit Sharma <rohit2sharma95@gmail.com>
This commit is contained in:
alpadev
2021-03-02 15:55:44 +01:00
committed by GitHub
parent 6d93a1371a
commit 48a95f7280
15 changed files with 131 additions and 166 deletions

View File

@@ -11,57 +11,47 @@
* ------------------------------------------------------------------------
*/
const mapData = (() => {
const storeData = {}
let id = 1
return {
set(element, key, data) {
if (typeof element.bsKey === 'undefined') {
element.bsKey = {
key,
id
}
id++
}
const elementMap = new Map()
storeData[element.bsKey.id] = data
},
get(element, key) {
if (!element || typeof element.bsKey === 'undefined') {
return null
}
export default {
set(element, key, instance) {
if (!elementMap.has(element)) {
elementMap.set(element, new Map())
}
const keyProperties = element.bsKey
if (keyProperties.key === key) {
return storeData[keyProperties.id]
}
const instanceMap = elementMap.get(element)
return null
},
delete(element, key) {
if (typeof element.bsKey === 'undefined') {
return
}
// make it clear we only want one instance per element
// can be removed later when multiple key/instances are fine to be used
if (!instanceMap.has(key) && instanceMap.size !== 0) {
// eslint-disable-next-line no-console
console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`)
return
}
const keyProperties = element.bsKey
if (keyProperties.key === key) {
delete storeData[keyProperties.id]
delete element.bsKey
}
instanceMap.set(key, instance)
},
get(element, key) {
if (elementMap.has(element)) {
return elementMap.get(element).get(key) || null
}
return null
},
remove(element, key) {
if (!elementMap.has(element)) {
return
}
const instanceMap = elementMap.get(element)
instanceMap.delete(key)
// free up element references if there are no instances left for an element
if (instanceMap.size === 0) {
elementMap.delete(element)
}
}
})()
const Data = {
setData(instance, key, data) {
mapData.set(instance, key, data)
},
getData(instance, key) {
return mapData.get(instance, key)
},
removeData(instance, key) {
mapData.delete(instance, key)
}
}
export default Data