'use strict';
var isObject = require('isobject');
var Emitter = require('component-emitter');
var visit = require('collection-visit');
var toPath = require('to-object-path');
var union = require('union-value');
var del = require('unset-value');
var get = require('get-value');
var has = require('has-value');
var set = require('set-value');
function namespace(prop) {
function Cache(cache) {
if (prop) {
this[prop] = {};
}
if (cache) {
this.set(cache);
}
}
Emitter(Cache.prototype);
Cache.prototype.set = function(key, val) {
if (Array.isArray(key) && arguments.length === 2) {
key = toPath(key);
}
if (isObject(key) || Array.isArray(key)) {
this.visit('set', key);
} else {
set(prop ? this[prop] : this, key, val);
this.emit('set', key, val);
}
return this;
};
Cache.prototype.union = function(key, val) {
if (Array.isArray(key) && arguments.length === 2) {
key = toPath(key);
}
var ctx = prop ? this[prop] : this;
union(ctx, key, arrayify(val));
this.emit('union', val);
return this;
};
Cache.prototype.get = function(key) {
key = toPath(arguments);
var ctx = prop ? this[prop] : this;
var val = get(ctx, key);
this.emit('get', key, val);
return val;
};
Cache.prototype.has = function(key) {
key = toPath(arguments);
var ctx = prop ? this[prop] : this;
var val = get(ctx, key);
var has = typeof val !== 'undefined';
this.emit('has', key, has);
return has;
};
Cache.prototype.del = function(key) {
if (Array.isArray(key)) {
this.visit('del', key);
} else {
del(prop ? this[prop] : this, key);
this.emit('del', key);
}
return this;
};
Cache.prototype.clear = function() {
if (prop) {
this[prop] = {};
}
};
Cache.prototype.visit = function(method, val) {
visit(this, method, val);
return this;
};
return Cache;
}
function arrayify(val) {
return val ? (Array.isArray(val) ? val : [val]) : [];
}
module.exports = namespace();
module.exports.namespace = namespace;