| 1 |
"use strict"; |
| 2 |
|
| 3 |
var indexOf = require("es5-ext/array/#/e-index-of") |
| 4 |
, create = Object.create; |
| 5 |
|
| 6 |
module.exports = function (length) { |
| 7 |
var lastId = 0, map = [[], []], cache = create(null); |
| 8 |
return { |
| 9 |
get: function (args) { |
| 10 |
var index = 0, set = map, i; |
| 11 |
while (index < length - 1) { |
| 12 |
i = indexOf.call(set[0], args[index]); |
| 13 |
if (i === -1) return null; |
| 14 |
set = set[1][i]; |
| 15 |
++index; |
| 16 |
} |
| 17 |
i = indexOf.call(set[0], args[index]); |
| 18 |
if (i === -1) return null; |
| 19 |
return set[1][i] || null; |
| 20 |
}, |
| 21 |
set: function (args) { |
| 22 |
var index = 0, set = map, i; |
| 23 |
while (index < length - 1) { |
| 24 |
i = indexOf.call(set[0], args[index]); |
| 25 |
if (i === -1) { |
| 26 |
i = set[0].push(args[index]) - 1; |
| 27 |
set[1].push([[], []]); |
| 28 |
} |
| 29 |
set = set[1][i]; |
| 30 |
++index; |
| 31 |
} |
| 32 |
i = indexOf.call(set[0], args[index]); |
| 33 |
if (i === -1) { |
| 34 |
i = set[0].push(args[index]) - 1; |
| 35 |
} |
| 36 |
set[1][i] = ++lastId; |
| 37 |
cache[lastId] = args; |
| 38 |
return lastId; |
| 39 |
}, |
| 40 |
delete: function (id) { |
| 41 |
var index = 0, set = map, i, path = [], args = cache[id]; |
| 42 |
while (index < length - 1) { |
| 43 |
i = indexOf.call(set[0], args[index]); |
| 44 |
if (i === -1) { |
| 45 |
return; |
| 46 |
} |
| 47 |
path.push(set, i); |
| 48 |
set = set[1][i]; |
| 49 |
++index; |
| 50 |
} |
| 51 |
i = indexOf.call(set[0], args[index]); |
| 52 |
if (i === -1) { |
| 53 |
return; |
| 54 |
} |
| 55 |
id = set[1][i]; |
| 56 |
set[0].splice(i, 1); |
| 57 |
set[1].splice(i, 1); |
| 58 |
while (!set[0].length && path.length) { |
| 59 |
i = path.pop(); |
| 60 |
set = path.pop(); |
| 61 |
set[0].splice(i, 1); |
| 62 |
set[1].splice(i, 1); |
| 63 |
} |
| 64 |
delete cache[id]; |
| 65 |
}, |
| 66 |
clear: function () { |
| 67 |
map = [[], []]; |
| 68 |
cache = create(null); |
| 69 |
}, |
| 70 |
}; |
| 71 |
}; |