plain-immutable
Version:
Make plain json data(array and object) immutable
55 lines (46 loc) • 2.14 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.isReactElement = isReactElement;
exports.isPlainObject = isPlainObject;
exports.stringify = stringify;
exports.validateKeyInKeyPath = validateKeyInKeyPath;
exports.validateKey = validateKey;
// react element is plain object too, so we need escape it from isPlainObject
// see https://github.com/facebook/react/blob/v15.0.1/src/isomorphic/classic/element/ReactElement.js#L21
var REACT_ELEMENT_TYPE_SYMBOL = typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element');
var REACT_ELEMENT_TYPE_NUMBER = 0xeac7;
function isReactElement(value) {
return value && (value.$$typeof === REACT_ELEMENT_TYPE_SYMBOL || value.$$typeof === REACT_ELEMENT_TYPE_NUMBER);
}
function isPlainObject(value) {
if (!value) return false;
var proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
var _toString = Object.prototype.toString;
function stringify(value) {
if (Array.isArray(value)) return '[' + value + ']';
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (type === 'string') return JSON.stringify(value);
if (value && type === 'object') {
return _toString.call(value);
}
return String(value);
}
function validateKeyInKeyPath(keyPath, key) {
var type = typeof key === 'undefined' ? 'undefined' : _typeof(key);
if (type !== 'string' && type !== 'number' || key === '') {
throw new TypeError('Invalid key path: ' + stringify(keyPath) + ', expect number or non-empty string in array');
}
return key;
}
function validateKey(key) {
var type = typeof key === 'undefined' ? 'undefined' : _typeof(key);
if (type !== 'string' && type !== 'number' || key === '') {
throw new Error('Invalid key: ' + stringify(key) + ', expect number or non-empty string');
}
return key;
}