remove multi charachter in sentence (angular 9) - javascript

I have this json reponse :
id: 30
tableName: "UserCredit"
keyValues: "{"Id":39}"
oldValues: "{"CoinLastUpdate":"2020-02-18T14:18:13.5155426+00:00","ScoreLastUpdate":"2020-02-18T14:18:13.5155429+00:00"}"
newValues: "{"CoinLastUpdate":"2020-02-18T14:18:15.7325823+00:00","ScoreLastUpdate":"2020-02-18T14:18:15.7325826+00:00"}"
auditType: "Update"
createdOnUtc: "2020-02-18T14:18:15.7338989Z"
createdByRefId: 39
I want to find the difference between oldValues and newValues then I write this code :
setOldNewValue(item: DeiffrentModel): void {
let oldValue;
let newValue;
console.log(item.oldValues)
if (item.newValues !== null) {
newValue = item.newValues.split(',');
}
if (item.oldValues !== null) {
oldValue = item.oldValues.split(',');
}
for (let index = 0; index < newValue.length; index++) {
let addModel = {} as DeifferModel;
addModel.field = 'id';
addModel.newValue = newValue[index];
console.log(oldValue)
if (oldValue !== undefined) {
addModel.oldValue = oldValue[index]
}
this.differModel.push(addModel);
}
this.findDiffrent = _.difference(newValue, oldValue);
}
Now I have this problem :
**** I create in newValue and oldValue array of value but it shows like this :
0: "CoinLastUpdate":"2020-02-18T14:18:13.5155426+00:00"
1: "ScoreLastUpdate":"2020-02-18T14:18:13.5155429+00:00"}
but I need just 2020-02-18T14:18:13.5155429+00:00
How can I solve this problem?

You should use JSON structure instead of parsing a string manually.
I would also use DeifferModel as a class instead of an interface, so you can init items more easily:
// in a xxx.model.ts file
export class DeifferModel {
constructor(public field, public newValue, public oldValue) {}
}
// in your component
setOldNewValue(item: DeiffrentModel): void {
if (item.newValues) {
newValue = JSON.parse(item.newValues);
}
if (item.oldValues) {
oldValue = JSON.parse(item.oldValues);
}
Object.keys(newValue).foreach(key => {
const addModel = new DeifferModel('id', newValue[key], oldValue[key]);
this.differModel.push(addModel);
});
this.findDiffrent = _.difference(newValue, oldValue); // no use of "this.differModel" ?
}

Insteading of storing these as an array, parse the values to an object
if (item.newValues !== null) {
newValue = item.newValues.split(',');
}
if (item.oldValues !== null) {
oldValue = item.oldValues.split(',');
}
to
oldValue = JSON.parse(oldValues);
newValue = JSON.parse(newValues);
You can find the difference in milliseconds like this:
CoinLastUpdateDiff = Math.abs(new Date(newValue.CoinLastUpdate) - new Date(oldValue.CoinLastUpdate));

Related

How to reduce congnitive complexity from 10 to 6 for a function in JavaScript

I have a trouble reducing the cognitive complexity here for this function.I tried to separate the contents inside the forEach as another function and by calling it in getCars function but failed. Could anyone please help?
const getCars = (cars, config, types) => {
const {
carName
} = types;
const carObject = {};
const carsRange = () => {}
let carRange = carsRange(cars);
Object.entries(cars).forEach(([key, value]) => {
if (key === 'sedan' && value) {
const carRangeVal = value.split(' ');
const year = carRangeVal[1];
const model = carRangeVal[0].substring(1, 2);
carRange = generateCarRange(year, model);
}
if (key === 'suv' && value) {
const carRangeVal = value.split(' ');
const year = carRangeVal[1];
const model = carRangeVal[0];
carObject['model'] = true;
carRange = checkYear(year, model);
}
if (value) {
carObject[key] = value;
}
});
if (
config.header === 'TEST A' ||
config.header === 'TEST B'
) {
carObject['carName'] = carName[0].id;
}
carObject['configName'] = config.header;
carObject['contractStartDate'] = carsRange[0];
carObject['contractEndDate'] = carsRange[1];
return carObject;
};
console.log(getCars({}, {}, {}));
You could shorten the code in the .forEach function:
[year,model] = value.split(' '); // destructuring assignment
if (key === 'sedan' && value) {
model = model.substring(1, 2);
carRange = generateCarRange(year, model);
}
if (key === 'suv' && value) {
carObject['model'] = true;
carRange = checkYear(year, model);
}
It would be helpful to know the input data.
I have an inkling that you may be better off using .map() instead of .forEach().
Why do you have two functions (generateCarRange() and checkYear()) to get carRange?
(I find it helpful to use Hungarian Notation to always know the type of my variables.)

Convert javascript class instance to plain object preserving methods

I want to convert an instance class to plain object, without losing methods and/or inherited properties. So for example:
class Human {
height: number;
weight: number;
constructor() {
this.height = 180;
this.weight = 180;
}
getWeight() { return this.weight; }
// I want this function to convert the child instance
// accordingly
toJSON() {
// ???
return {};
}
}
class Person extends Human {
public name: string;
constructor() {
super();
this.name = 'Doe';
}
public getName() {
return this.name;
}
}
class PersonWorker extends Person {
constructor() {
super();
}
public report() {
console.log('I am Working');
}
public test() {
console.log('something');
}
}
let p = new PersonWorker;
let jsoned = p.toJSON();
jsoned should look like this:
{
// from Human class
height: 180,
weight: 180,
// when called should return this object's value of weight property
getWeight: function() {return this.weight},
// from Person class
name: 'Doe'
getName(): function() {return this.name},
// and from PersonWorker class
report: function() { console.log('I am Working'); },
test: function() { console.log('something'); }
}
Is this possible to achieve, and if so, how?
In case you're wondering, I need this because I am using a framework that, unfortunately, accepts as input only an object, whereas I am trying to use TypeScript and class inheritance.
Also, I am doing the above conversion once so performance isn't an issue to consider.
The solutions consisting of iterating through object properties will not work if the compiler's target option is set to es6. On es5, the existing implementations by iterating through object properties (using Object.keys(instance)) will work.
So far, I have this implementation:
toJSON(proto?: any) {
// ???
let jsoned: any = {};
let toConvert = <any>proto || this;
Object.getOwnPropertyNames(toConvert).forEach((prop) => {
const val = toConvert[prop];
// don't include those
if (prop === 'toJSON' || prop === 'constructor') {
return;
}
if (typeof val === 'function') {
jsoned[prop] = val.bind(this);
return;
}
jsoned[prop] = val;
const proto = Object.getPrototypeOf(toConvert);
if (proto !== null) {
Object.keys(this.toJSON(proto)).forEach(key => {
if (!!jsoned[key] || key === 'constructor' || key === 'toJSON') return;
if (typeof proto[key] === 'function') {
jsoned[key] = proto[key].bind(this);
return;
}
jsoned[key] = proto[key];
});
}
});
return jsoned;
}
But this is still not working. The resulted object includes only all the properties from all classes but only methods from PersonWorker.
What am I missing here?
Lots of answers already, but this is the simplest yet by using the spread syntax and de-structuring the object:
const {...object} = classInstance
This is what's working for me
const classToObject = theClass => {
const originalClass = theClass || {}
const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(originalClass))
return keys.reduce((classAsObj, key) => {
classAsObj[key] = originalClass[key]
return classAsObj
}, {})
}
Ok, so the implementation in my OP was wrong, and the mistake was simply stupid.
The correct implementation when using es6 is:
toJSON(proto) {
let jsoned = {};
let toConvert = proto || this;
Object.getOwnPropertyNames(toConvert).forEach((prop) => {
const val = toConvert[prop];
// don't include those
if (prop === 'toJSON' || prop === 'constructor') {
return;
}
if (typeof val === 'function') {
jsoned[prop] = val.bind(jsoned);
return;
}
jsoned[prop] = val;
});
const inherited = Object.getPrototypeOf(toConvert);
if (inherited !== null) {
Object.keys(this.toJSON(inherited)).forEach(key => {
if (!!jsoned[key] || key === 'constructor' || key === 'toJSON')
return;
if (typeof inherited[key] === 'function') {
jsoned[key] = inherited[key].bind(jsoned);
return;
}
jsoned[key] = inherited[key];
});
}
return jsoned;
}
Here is the implementation for the toJSON() method. We are copying over the properties & methods from the current instance to a new object and excluding the unwanted methods i.e. toJSON and constructor.
toJSON() {
var jsonedObject = {};
for (var x in this) {
if (x === "toJSON" || x === "constructor") {
continue;
}
jsonedObject[x] = this[x];
}
return jsonedObject;
}
I have tested the object returned by toJSON() in Chrome and I see the object behaving the same way as you are expecting.
I'm riffing on Alex Cory's solution a lot, but this is what I came up with. It expects to be assigned to a class as a Function with a corresponding bind on this.
const toObject = function() {
const original = this || {};
const keys = Object.keys(this);
return keys.reduce((classAsObj, key) => {
if (typeof original[key] === 'object' && original[key].hasOwnProperty('toObject') )
classAsObj[key] = original[key].toObject();
else if (typeof original[key] === 'object' && original[key].hasOwnProperty('length')) {
classAsObj[key] = [];
for (var i = 0; i < original[key].length; i++) {
if (typeof original[key][i] === 'object' && original[key][i].hasOwnProperty('toObject')) {
classAsObj[key].push(original[key][i].toObject());
} else {
classAsObj[key].push(original[key][i]);
}
}
}
else if (typeof original[key] === 'function') { } //do nothing
else
classAsObj[key] = original[key];
return classAsObj;
}, {})
}
then if you're using TypeScript you can put this interface on any class that should be converted to an object:
export interface ToObject {
toObject: Function;
}
and then in your classes, don't forget to bind this
class TestClass implements ToObject {
toObject = toObject.bind(this);
}
This solution will lose methods, but it is a very simple solution to convert a class instance to an object.
obj = JSON.parse(JSON.stringify(classInstance))
using Lodash
This method isn't recursive.
toPlainObject() {
return _.pickBy(this, item => {
return (
!item ||
_.isString(item) ||
_.isArray(item) ||
_.isNumber(item) ||
_.isPlainObject(item)
);
});
}

Create a JavaScript object from string

I'm trying to create a JavaScript function that creates an object using strings for structure and fills it from DOM data.
For example, the following strings could look like this:
some.example.here = "hello"
some.example.there = "hi"
other.example = "heyo"
Which should create this object:
{
some: {
example: {
here: "hello",
there: "hi"
},
other: {
example: "heyo
}
}
The data as said comes from DOM and is being load at the code segment labeled "read data into object". The data loads fine and the object structure is being setup fine as well, but the data is not being put into the data field.
Here's the code for the function:
function getDataFromElement(element) {
obj = {};
$(element)
.find("[data-value]")
.each(function() {
// create object node
valueObj = {};
currentValueObj = valueObj;
$.each($(this).attr("data-value").split("."), function(i, objpath) {
currentValueObj[objpath] = {};
currentValueObj = currentValueObj[objpath];
});
// read data into object
if($(this).is("[data-putvalue]") && $(this).attr("data-putvalue") != "html") {
currentValueObj = $(this).attr($(this).attr("data-putvalue"));
} else {
currentValueObj = $(this).html();
}
console.log(currentValueObj);
// combine with previous gathered data
obj = $.extend(true, {}, obj, valueObj);
});
return obj;
}
Does anyone know what to do?
I would do it like this:
var createObject = function(model, name, value) {
var nameParts = name.split("."),
currentObject = model;
for (var i in nameParts) {
var part = nameParts[i];
if (i == nameParts.length-1) {
currentObject[part] = value;
break;
}
if (typeof currentObject[part] == "undefined") {
currentObject[part] = {};
}
currentObject = currentObject[part];
}
};
And then use it like that:
var model = {};
createObject(model, "some.example.here", "hello");
createObject(model, "some.example.there", "hi");
createObject(model, "other.example", "heyo");
Probably this can suit you (adapted from another project of mine, adapt and use as needed):
NOTE the element's name is taken as key and value as the value
function fields2model( $elements, dataModel )
{
$elements.each(function( ){
var $el = $(this),
name = $el.attr('name'),
key, k, i, o, val
;
key = name;
val = $el.val() || '';
k = key.split('.'); o = dataModel;
while ( k.length )
{
i = k.shift( );
if ( k.length )
{
if ( !o.hasOwnProperty( i ) ) o[ i ] = /^\d+$/.test( k[0] ) ? [ ] : { };
o = o[ i ];
}
else
{
o[ i ] = val;
}
}
});
}
Example use:
<input name="some.example.here" value="hello" />
<input name="some.example.there" value="hi" />
var model = {};
fields2model($('input,textarea,select'), model);
The example elements above will give the below model:
model = {
some: {
example: {
here: "hello",
there: "hi"
}
};
Some functional implementation:
const value = 'hello';
'some.example.here'.split('.').reverse().reduce((reduction, segment, index) => {
const result = {};
if (index === 0) {
result[segment] = value;
} else {
result[segment] = reduction;
}
return result;
}, {})
#theFreedomBanana +1
Works for me
const magicFunction = (string, value) =>
string
.split('.')
.reverse()
.reduce((acc, cur, index) => ({ [cur]: index === 0 ? value : acc }), {});

LocalStorage and JSON.stringify JSON.parse

I have been working on a project that allows the user to submit memories about a place they have visited and tracks the location of when the memory was submitted. My only problem is trying to use localStorage with the app, I read about the JSON.stringify and JSON.parse, and don't understand how to use them in my code yet.
This is my form.js
It processes the form and grabs the text fields. It clears the form when the add button(on the display details page) or the enter details button is clicked. Finally it receives the information and sends out the message back to the window.
function processForm(){
var locate = document.myform.locate.value;
var details = document.myform.details.value;
var storeData = [];
localStorage.setItem("locate", JSON.stringify(locate));
localStorage.setItem("details", JSON.stringify(details));
alert("Saved: " + localStorage.getItem("locate") + ", and " + localStorage.getItem("details"));
var date = new Date,
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
ampm = hour > 12 ? "PM" : "AM";
hour = hour % 12;
hour = hour ? hour : 12; // zero = 12
minute = minute > 9 ? minute : "0" + minute;
hour = hour > 9 ? hour : "0" + hour;
date = month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + ampm;
localStorage.setItem("date", JSON.stringify(date));
storeData.push(locate, details, date);
localStorage.setItem("storeData", JSON.stringify(storeData));
}
function clearForm(){
$('#myform').get(0).reset();
}
function retrieveFormInfo(){
var data = JSON.parse(localStorage.getItem("storeData"));
var locate = JSON.parse(localStorage.getItem("locate"));
$("#locate2").html("Place: " + locate);
var details = JSON.parse(localStorage.getItem("details"));
$("#details2").html("Description: " + details);
var date = JSON.parse(localStorage.getItem("date"));
$("#date").html(date);
}
But the major problem I am running into is I do know how to take that information in correctly using the JSON.stringify and JSON.parse and appending it to the window with html elements dynamically, Mainly like a list of memories.
Any help is appreciated!
localStorage stores key value pairs as strings only (you can use integer for keys but they get converted to string automatically).
Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings) reference
let's say you have an array to be stored with each item being a json object.
You got 2 options:
Option 1:
stringify every item and store in locaStorage
var item = {input1: 'input1value', input2: 'input2value' };
localStorage.setItem( itemIndex, JSON.stringify(item) );
to retrive the items iterate over localStorage items and then convert the item to JSON object:
for(var i=0;i<localStorage.length; i++) {
var key = localStorage.key( i );
var item = JSON.parse( localStorage.getItem( key ) );
}
Option 2:
stringify the entire array and store in localStorage
localStorage.setItem( 'memoriesdata', JSON.stringify( arr ) );
to read the data read the item as string then convert to JSON object
var arr = JSON.parse( localStorage.getItem('memoriesdata') );
First get values of your input fields into a javascript object.
var myMemory = {};
myMemory.location = document.getElementById('location').value;
myMemory.description = document.getElementById('description').value;
Now save myMemory to localStorage,this can be done on a form submission or a button press. We can store as an array of memories and add item to it every time.
//if user already has memories in local, get that array and push into it.
//else create a blank array and add the memory.
memories = localStorage.getItem('memories') ?
JSON.parse(localStorage.getItem('memories')) :
[];
memories.push(myMemory);
localStorage.setItem('memories', JSON.stringify(memories));
I use this Storage implementation. It's inspired by many storage plugins out there... It handles any value serilizable by JSON.stringify function, and should work xbrowser (and in 'cookie-disabled' firefox):
//
// api:
//
// .clear() empties storage
// .each() loops storage (key, value) pairs
// .fetch() get a value by key
// .has() checks if there is a key set
// .ls() lists all keys
// .raw() string value actually stored
// .reload() reads in serialized data
// .rm() removes key(s)
// .set() setup value(s)
// .type() storage type used 'localStorage/globalStorage/userData'
// .valid() is storage engine setup correctly
//
;
((function(name, def, glob, doc) {
// add 'store' id to globals
this[name] = def(glob, doc);
}).call(
this, "store", function(glob, doc) {
// private (function) store version
var stclient;
var driver = {
// obj : storage_native{},
// type : storage_type
};
var engine = {
// read : (func),
// write : (func)
};
var _ = {
a: Array.prototype,
del: function(node) { // , ...fields
_.slc(arguments, 1).
forEach(function(field) {
delete this[field];
}, node);
return node;
},
each: function(array, callback, context) {
context ||
(context = array);
array.
some(function() {
return false === callback.apply(context, arguments);
});
return array;
},
hasown: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
jsdc: JSON.parse, // decode
jsec: JSON.stringify, // encode
keys: Object.keys, // shimed .keys
ns: "storage5", // single property name to keep serialized storage data under
object: null, // parsed storage data
slc: Function.prototype.call.bind(Array.prototype.slice),
test: {
isemptyobj: function(node) {
for (var x in node)
return false;
return true;
},
isplainobj: function(node) {
return '[object Object]' == Object.prototype.toString.call(node);
},
},
testval: 'storage' + Math.random(), // test value for implementation check
rig: function(target, items) {
for (var field in items)
if (items.hasOwnProperty(field))
target[field] = items[field];
return target;
},
clone: function(node) {
return _.jsdc(_.jsec(node));
},
puts: function() {
engine.write(_.jsec(_.object));
},
};
stclient = function storage5() {
return arguments.length ?
storage5.set.apply(storage5, arguments) :
storage5.fetch();
};
// _init on load|ready
window.addEventListener('load', _init, false);
return _.rig(stclient, {
clear: function() {
return _.object = {}, _.puts(), this;
},
each: function(callback, context) {
context ||
(context = this.fetch());
_.each(this.ls(), function(field) {
return callback.call(context, field, this.fetch(field));
}, this);
return this;
},
fetch: function(key) {
return (arguments.length) ?
_.object[key] : _.clone(_.object);
},
has: function(name) {
return _.hasown(_.object, name);
},
ls: function() {
return _.keys(_.object);
},
raw: function() {
return engine.read();
},
reload: _load,
rm: function() {
_.del.apply(null, _.a.concat.apply([_.object], arguments));
return _.puts(), this;
},
set: function(input, value) {
var len = arguments.length;
var flag = 1;
if (len) {
if (_.test.isplainobj(input)) {
_.keys(input).
forEach(function(field) {
_.object[field] = input[field];
});
} else {
if (1 < len)
_.object[input] = value;
else
flag = 0;
}
flag && _.puts();
}
return this;
},
type: function() {
return driver.type || null;
},
valid: function() {
return !_.test.isemptyobj(driver);
},
});
function _init() {
var flag = 0;
var stnative;
if ("localStorage" in glob) {
try {
if ((stnative = glob["localStorage"])) {
// inits localStorage
_initlocst(stnative, driver, engine);
flag = 1;
}
} catch (e) {}
}
if (!flag) {
if ("globalStorage" in glob) {
try {
if ((stnative = glob["globalStorage"])) {
// inits globalStorage
_initglobst(stnative, driver, engine);
flag = 1;
}
} catch (e) {}
}
if (!flag) {
// inits userDataStorage
_initusrdatast(doc.createElement(_.ns), driver, engine);
}
}
// parse serialized storage data
_load();
}
function _initlocst(stnative, driver, engine) {
stnative[_.testval] = _.testval;
if (_.testval === stnative[_.testval]) {
try {
stnative.removeItem(_.testval);
} catch (e) {
try {
delete stnative[_.testval];
} catch (e) {}
}
driver.obj = stnative;
driver.type = "localStorage";
engine.read = function() {
return driver.obj[_.ns];
};
engine.write = function(stringvalue) {
driver.obj[_.ns] = stringvalue;
return stringvalue;
};
}
}
function _initglobst(stnative, driver, engine) {
var host = glob.location.hostname;
driver.obj = (/localhost/i).test(host) ?
stnative["localhost.localdomain"] : stnative[host];
driver.type = "globalStorage";
engine.read = function() {
return driver.obj[_.ns];
};
engine.write = function(stringvalue) {
driver.obj[_.ns] = stringvalue;
return stringvalue;
};
}
function _initusrdatast(node, driver, engine) {
try {
node.id = _.ns;
node.style.display = "none";
node.style.behavior = "url('#default#userData')";
doc.
getElementsByTagName("head")[0].
appendChild(node);
node.load(_.ns);
node.setAttribute(_.testval, _.testval);
node.save(_.ns);
if (_.testval === node.getAttribute(_.testval)) {
try {
node.removeAttribute(_.testval);
node.save(_.ns);
} catch (e) {}
driver.obj = node;
driver.type = "userData";
engine.read = function() {
return driver.obj.getAttribute(_.ns);
};
engine.write = function(stringvalue) {
driver.obj.setAttribute(_.ns, stringvalue);
driver.obj.save(_.ns);
return stringvalue;
};
}
} catch (e) {
doc.
getElementsByTagName("head")[0].
removeChild(node);
}
node = null;
}
function _load() {
try {
_.object = _.jsdc((engine.read() || engine.write("{}")));
} catch (e) {
_.object = {};
}
}
}, window, document));
//eof
Vanilla JS:
var printStorageBody = function () {
var body = document.querySelector("body");
var pre = document.createElement("pre");
body.innerHTML = "";
pre.innerText = JSON.stringify(localStorage, null, '\t');
body.appendChild(pre);
}
jQuery:
var printStorageBody = function () {
$("body").html("");
$("<pre>")
.text(JSON.stringify(localStorage, null, '\t'))
.appendTo("body");
}

Array being reset to undefined after adding items to it

I am trying to construct a hierarchy (tree structure) using JavaScript. For that, I wrote a Node class that represents a node in the tree. When I retrieve the data from the database, it's all being retrieved properly (i.e: the root node has the ParentId as null, it has 3 children that point to it as the parent, and the descendant nodes are set up properly as well...). But when I try to map them to my JavaScript model, the Children property of the root node is ending up being undefined. I do not know how that could be posible even though during runtime, when I output the contents of the Children property in the console I can see the children nodes being added to it. Here's my code:
var Node = function (obj) {
var self = this;
var isDefined = obj != undefined;
self.hasChildren = function () {
return self.Children.length > 0;
};
self.hasParent = function () {
var p = self.ParentId;
return !(p == null || p == undefined || p == 0);
};
self.addChildren = function (objArray) {
if (!$.isArray(self.Children)) {
self.Children = [];
}
for (var i = 0; i < objArray.length; i++) {
self.addChild(objArray[i]);
}
};
self.addChild = function (obj) {
if (obj instanceof Node) {
self.Children.push(obj);
} else {
var n = new Node(obj);
self.Children.push(n);
}
};
self.removeChild = function (n) {
var index = self.Children.indexOf(n);
if (index > -1) {
self.Children.splice(index, 1);
}
};
self.Id = isDefined ? obj.Id : null;
self.ParentId = isDefined ? obj.ParentId : null;
self.Name = isDefined ? obj.Name : '';
self.Children = isDefined ? self.addChildren(obj.Children) : [];
self.TypeId = isDefined ? obj.TypeId : null;
};
The way I thought about the addChildren method, is that I would pass the raw JSON object coming from the server into the constructor of the Node object and then in case it has any children (which essentially have the same properties as the parent), addChildren will be called which will in turn create a new Node for each element. Eventually, the tree will be built recursively.
So where did I go wrong? Why does the Children property end up being undefined?
self.Children = isDefined ? self.addChildren(obj.Children) : [];
You are setting self.Children equal to the return of self.addChildren(). That function has no return.
Here is a couple things I would recommend
function Node(obj) {
// clean constructor moving function definitions to prototype
var self = this;
// ensure that we at least have an object passed in
obj = obj || {};
// default values at the top
self.Id = null;
self.ParentId = null;
self.Name = '';
self.Children = [];
self.TypeId = null;
// fold in data with $.extend, no need to specify each key manually
// third object is to overwrite any added Children as those need to be handled seperately
$.extend(self, obj, { Children : [] });
// if we have children, add them using the addChildren method
if (typeof obj.Children !== undefined && $.isArray(obj.Children)) {
self.addChildren(obj.Children);
}
}
// using prototype to reduce memory footprint
Node.prototype.hasChildren = function () {
return this.Children.length > 0;
};
Node.prototype.hasParent = function () {
var p = this.ParentId;
return !(p == null || p == undefined || p == 0);
};
Node.prototype.addChildren = function (objArray) {
for (var i = 0; i < objArray.length; i++) {
this.addChild(objArray[i]);
}
};
Node.prototype.addChild = function (obj) {
if (obj instanceof Node) {
this.Children.push(obj);
} else {
var n = new Node(obj);
this.Children.push(n);
}
};
Node.prototype.removeChild = function (n) {
var index = this.Children.indexOf(n);
if (index > -1) {
this.Children.splice(index, 1);
}
};
Then I can use this like so:
test = new Node({ Id : "Something", Children : [{ Id : "Interior", Children : [] }] })
Using prototype you reduce the memory footprint and don't create a function reference to each interior function for each Node you create. Each Node one still will reference it's internal data via a this variable.

Categories

Resources