extendable-immutable
Version:
Wraps around Immutable.js to turn it inheritable
70 lines (55 loc) • 1.82 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = extendable;
var _createExtendable = require('./util/createExtendable');
var _createExtendable2 = _interopRequireDefault(_createExtendable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function extendable(Base) {
var NAME = Base.prototype.constructor.name;
var emptyBase = new Base();
var exampleBase = void 0;
if (emptyBase.add) {
exampleBase = emptyBase.add('a');
} else if (emptyBase.set) {
exampleBase = emptyBase.set('a', 'b');
} else if (emptyBase.push) {
exampleBase = emptyBase.push('a');
} else {
throw new Error('extendable: `' + NAME + '` is not supported.');
}
var KEYS = Object.keys(exampleBase);
var EMPTY = KEYS.reduce(function (acc, key) {
acc[key] = emptyBase[key];
return acc;
}, {});
function copy(val, update) {
return KEYS.reduce(function (acc, key) {
acc[key] = update[key];
return acc;
}, val);
}
function empty(val) {
return Object.keys(EMPTY).reduce(function (acc, key) {
acc[key] = EMPTY[key];
return acc;
}, val);
}
function ExtendableWrapper(val) {
var instance = this;
if (instance === undefined) {
instance = new ExtendableWrapper(val);
}
return instance.__wrapImmutable(new Base(val));
}
ExtendableWrapper['is' + NAME] = function is(obj) {
return obj && obj instanceof ExtendableWrapper;
};
ExtendableWrapper.prototype = (0, _createExtendable2.default)(Base, copy, empty);
ExtendableWrapper.prototype.constructor = ExtendableWrapper;
ExtendableWrapper.prototype.toString = function toString() {
return 'Extendable.' + Base.prototype.toString.call(this);
};
return ExtendableWrapper;
}
;