jrwalt4 / arga

A JavaScript implementation of the ADO.NET DataSet pattern
MIT License
0 stars 0 forks source link

Support for objects stored in DataRow #1

Open jrwalt4 opened 8 years ago

jrwalt4 commented 8 years ago

Use a function to deep copy values during acceptChanges.

function flattenPrototype(a) {
  var obj = (Array.isArray(a)) ? [] : Object.create(null);
  for (var key in a) {
    var value;
    if (typeof a[key] === "object") {
      value = flattenPrototype(a[key]);
    } else value = a[key];
    obj[key] = value;
  }
  return obj;
}

Also, use Object.create(null) for DataRow._original

jrwalt4 commented 8 years ago

a better deep copy algorithm to catch circular references

function flattenPrototype(p, depth, doNotInclude) {
  depth = (depth !== void 0) ? depth  || 5;
  doNotInclude = (Array.isArray(doNotInclude)) ? doNotInclude || [];
  if(doNotInclude.indexOf(p) < 0) {
    doNotInclude.push(p);
  }
  var obj = (Array.isArray(p)) ? [] : Object.create(null);
  for (var key in p) {
    if (typeof p[key] === "object") {
      // only add the object if we haven't reached max depth
      if(depth > 0) {
        // only add the object if it is not part of our doNotInclude list,
        // which prevents circular references.
        if(doNotInclude.indexOf(p[key]) < 0) {
          obj[key] = flattenPrototype(p[key], depth - 1, doNotInclude.slice());
        } else {
          console.warn('circular ref:', p[key])
        }
      }
    } else {
      obj[key] = p[key];
    }
  }
  return obj;
}