Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function deepClone(val) {
- if (!isObject(val)) {
- return val;
- }
- if (val instanceof Array) {
- return val.map(deepClone);
- }
- var clone = {};
- var prop;
- for (prop in val) {
- clone[prop] = deepClone(val[prop]);
- }
- return clone;
- }
- function assert(condition) {
- if (!condition) {
- throw new Error('Assertion failed');
- }
- }
- function isObject(val) {
- return typeof val === 'object' && val !== null;
- }
- function deepEquals(val1, val2) {
- if (val1 instanceof Array) {
- if (!(val2 instanceof Array) || val1.length !== val2.length) {
- return false;
- }
- return val1.every(function (val1Item, index) {
- return deepEquals(val1Item, val2[index]);
- });
- }
- if (!isObject(val1) || !isObject(val2)) {
- return val1 === val2;
- }
- var val1Keys = Object.keys(val1);
- if (val1Keys.length !== Object.keys(val2).length) {
- return false;
- }
- return val1Keys.every(function (val1Key) {
- return val2.hasOwnProperty(val1Key) && deepEquals(val1[val1Key], val2[val1Key]);
- });
- }
- var data = {
- name: 'Paddy',
- address: {
- town: 'Lerum',
- country: 'Sweden'
- }
- };
- var clone = deepClone(data);
- assert(deepEquals(data, clone));
- clone.address.street = 'Test street';
- assert(!deepEquals(data, clone));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement