Javascript creating object in if not carrying over - javascript

This is my code:
var cleanname = v.name.replace(/\s/g, "_").toLowerCase();
if(typeof(kpiValues[v.category]) === "undefined") {
kpiValues[v.category] = {};
if(typeof(kpiValues[v.category][cleanname] === "undefined")) {
kpiValues[v.category][cleanname] = [];
}
}
if(departments !== "default") {
if(typeof(kpiValues[v.category][cleanname][0]) === "undefined") {
kpiValues[v.category][cleanname][0] = {};
kpiValues[v.category][cleanname][0].value = 0;
}
}
This line:
if(typeof(kpiValues[v.category][cleanname][0]) === "undefined") {
throws me an error, and I am completely confused on why. In the first if-block, I ensure it builds out the object/array, but for some reason that I can't understand, it throws this error:
TypeError: Cannot read property '0' of undefined
Any suggestions?

typeof is not a function in Javascript so you can use like
typeof oprand
Consider this:
if(typeof kpiValues[v.category][cleanname][0] === "undefined") {

Related

Madcap Flare 11 - HTML5 output throws requirejs error - Mismatched anonymous define() module: function(C

I am building the customer manual on frontend using Madcam Flare 11 HTML5 output and referring the below js file but getting the error Uncaught Error: Mismatched anonymous define() module: function(C)
<script src="scripts/helpDoc/WHP/Default.js"></script>
After i load the Madcap library and runtime i am getting the below error. This error comes at very first time when i invoke the madcap flare methods.
require.min.js:13 Uncaught Error: Mismatched anonymous define() module: function () { 'use strict';
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var es6Promise = createCommonjsModule(function (module, exports) {
/*!
* #overview es6-promise - a tiny implementation of Promises/A+.
* #copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* #license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* #version v4.2.5+7f2b526d
*/
(function (global, factory) {
module.exports = factory();
}(commonjsGlobal, (function () { function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = void 0;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = void 0;
var customSchedulerFn = void 0;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof commonjsRequire === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var parent = trequire.min.js:13)
at L (require.min.js:41)
at Object.g [as require] (require.min.js:104)
at requirejs (require.min.js:126)
at MadCap.WebHelp.HelpSystem.LoadLanguage (Default.js:269)
at Default.js:269
at MadCap.WebHelp.HelpSystem.LoadBreakpoints (Default.js:269)
at MadCap.WebHelp.HelpSystem.<anonymous> (Default.js:269)
at XMLHttpRequest.OnreadystatechangeRemote (Default.js:241)

Binary Tree code - Cannot read property 'data' of undefined

class Node {
constructor(data, left, right) {
this.data = data;
this.left = left;
this.right = right;
}
}
class BST {
constructor() {
this.root = null
}
add(data) {
const node = this.root
if (node === null) {
this.root = new Node(data)
return
} else {
const searchTree = function (node) {
if (data < node.data) {
if (node.left === null) {
node.left = new Node(data)
return
} else if (node.left !== null) {
return searchTree(node.left)
}
} else if (data > node.data) {
if (node.right === null) {
node.right = new Node(data)
return
} else if (node.right !== null) {
return searchTree(node.right)
}
} else {
return null
}
}
return searchTree(node)
}
}
levelOrder() {
const arr = [];
const queue = [];
let node = this.root;
queue.push(node);
while(queue.length) {
node = queue.shift();
arr.push(node);
if(node.left !== null) queue.push(node.left);
if(node.rigth !== null) queue.push(node.right);
}
}
}
const tree = new BST()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
console.log(tree)
Error I keep getting
if (data < node.data) {
^
TypeError: Cannot read property 'data' of undefined
I made sure to double check my code and sometimes it works other times it doesn't....
Can anyone help with this and explain thinks I'm not understanding and what I need to look into.
The issue is that the node.left and node.right are undefined since you're not assigning them any values when creating a new node but you're checking them for strict equality with null like
node.left !== null
You just simply need to change your Node class to this :
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
OR
Use the Logcial NOT to check for a falsy value since undefined and null both are falsy values like
if( !node.left ){
.
.
}
Hope this helps !
making my comments an answer..
The problem is that node.left or node.right are not strictly null but sometimes undefined. So if you alter your comparisons to use weak equality for null which covers both null and undefined it will work.
Ie change ===null to ==null and !==null to !=null. Else make sure you intitialise left and right to null always, but using weak equality is better.
In fact in javascript (and other languages) you can simply use if (node) and if (node.left) and so on.. since either they will null/undefined or a Node instance (and not zero). So even simpler test.

Uncaught TypeError: undefined is not a function in knockout

I am trying to implement a filter functionality in a html table generated through knockout for each binding with the help of following code.
self.filteredStep1Records = ko.computed(function() {
return ko.utils.arrayFilter(self.step1BundleData(), function(bundle) {
self.pageNumber(0);
return (self.searchText().length == 0 || bundle.id.toLowerCase().indexOf(self.searchText().toLowerCase()) !== -1 || bundle.name.toLowerCase().indexOf(self.searchText().toLowerCase()) !== -1);
});
});
I am getting error as
"Uncaught TypeError: undefined is not a function" at following line:
return (self.searchText().length == 0 || bundle.id.toLowerCase().indexOf(self.searchText().toLowerCase()) !== -1 || bundle.name.toLowerCase().indexOf(self.searchText().toLowerCase()) !== -1);
Rest of the code includes:
this.searchText = ko.observable('');
this.step1BundleData = ko.observableArray();
function bundle(id,name){
this.id = ko.observable(id);
this.name = ko.observable(name);
this.selected = ko.observable(false);
}
Following Ajax request is used to create bundle:
getdata(8).done(function(data){
data = $.parseJSON(data);
$.each(data,function(index,value){
self.step1BundleData.push(new bundle(value.id,value.name));
});
});
I am not sure where I am going wrong.
Being defined as ko.observables...
function bundle(id,name){
this.id = ko.observable(id);
this.name = ko.observable(name);
this.selected = ko.observable(false);
}
...the id and name of each new bundle will be functions that you'll have to invoke to retrieve the value.
... || bundle.id().toLowerCase().indexOf(...
// ^^
Similar to how you're invoking self.searchText to retrieve its value:
return (self.searchText().length == 0 || ...
// ^^
The functions themselves won't have a toLowerCase() method.
console.log(typeof bundle.name); // 'function'
console.log(typeof bundle.name.toLowerCase); // 'undefined'
console.log(typeof bundle.name()); // 'string'
console.log(typeof bundle.name().toLowerCase); // 'function'
return (self.searchText().length == 0 || bundle.id().toLowerCase().indexOf(self.searchText().toLowerCase()) !== -1 || bundle.name().toLowerCase().indexOf(self.searchText().toLowerCase()) !== -1);

Node WebDriverJS executeScript behaviour

I have a WebDriverJS Node script with the following in the global scope of the application:
var helperFunctions = {
'getElementEssentials': function get(orig, tmp, level) {
var tmp = tmp || {};
var level = level || 0;
for(var i in orig) {
if(!orig[i]) { continue; }
if(typeof(orig[i]) === 'function' || typeof(orig[i]) === 'object' || level > 1) { continue; }
if(typeof(orig[i]) === 'array') { level++; get(orig[i], tmp, level); continue; }
tmp[i] = orig[i]; continue;
}
return tmp;
}
};
I want to pass this function in to driver.executeScript using something like this:
var evalSelectAll = function(selector, getElementEssentials) {
var els = document.querySelectorAll(selector);
var els2 = [];
for(var i in els) {
els2.push(getElementEssentials(els[i]));
}
var elsStringified = JSON.stringify(els2);
return elsStringified;
};
driver.executeScript(evalSelectAll, selector, helperFunctions.getElementEssentials).then( function(data) {
// things
});
selector relates to a CSS selector expression, so "a" or "div > h1" for example.
My understanding of executeScript is that for the first argument it can accept either a string or a function - a string will be evaluated on the target page, and a function will be executed on the target page, and that all subsequent arguments are additional data?
I get the following error when trying to run this (note that to keep things simple I just passed in a test object of {test: true}:
D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:1643
throw error;
^
UnknownError: {"errorMessage":"'function get(orig, tmp, level) {\r\n\t var tmp = tmp || {};\r\n\t var level = level || 0;\r\n\t for(var i in orig) {\r\n\t if(!orig[i]) { continue; }\r\n\t if(typeof(orig[i]) === 'function' || typeof(orig[i]) === 'object' || level > 1) { continue; }\r\n\t if(typeof(orig[i]) === 'array') { level++; get(orig[i], tmp, level); continue; }\r\n\t tmp[i] = orig[i]; continue;\r\n\t }\r\n\t return tmp;\r\n\t}' is not a function (evaluating 'getElementEssentials({test: true})')","request":{"headers":{"Accept":"application/json; charset=utf-8","Connection":"keep-alive","Content-Length":"903","Content-Type":"application/json;charset=UTF-8","Host":"192.168.0.7:56849"},"httpVersion":"1.1","method":"POST","post":"{\"script\":\"return (function (selector, getElementEssentials) {\\r\\n\\r\\n\\t\\t\\treturn getElementEssentials({test: true});\\r\\n\\r\\n\\t\\t\\tvar els = document.querySelectorAll(selector);\\r\\n\\t\\t\\t\\r\\n\\t\\t\\t/*var els2 = [];\\r\\n\\t\\t\\tfor(var i in els) {\\r\\n\\t\\t\\t\\tels2.push(getElementEssentials(els[i]));\\r\\n\\t\\t\\t}\\r\\n\\r\\n\\t\\t\\tvar elsStringified = JSON.stringify(els2);\\r\\n\\r\\n\\t\\t\\treturn elsStringified;*/\\r\\n\\r\\n\\t\\t}).apply(null, arguments);\",\"args\":[\"h1\",\"function get(orig, tmp, level) {\\r\\n\\t var tmp = tmp || {};\\r\\n\\t var level = level || 0;\\r\\n\\t for(var i in orig) {\\r\\n\\t
if(!orig[i]) { continue; }\\r\\n\\t if(typeof(orig[i]) === 'function' || typeof(orig[i]) === 'object' || level > 1) { continue; }\\r\\n\\t if(typeof(orig[i]) === 'array') { level++; get(orig[i], tmp, level); continue; }\\r\\n\\t tmp[i] = orig[i]; continue;\\r\\n\\t }\\r\\n\\t return tmp;\\r\\n\\t}\"]}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/c18c1ff0-0f25-11e4-a90e-a36273e3866b/execute"}}
at new bot.Error (D:\Git\mateserver\node_modules\selenium-webdriver\lib\atoms\error.js:109:18)
at Object.bot.response.checkResponse (D:\Git\mateserver\node_modules\selenium-webdriver\lib\atoms\response.js:106:9)
at D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:277:20
at D:\Git\mateserver\node_modules\selenium-webdriver\lib\goog\base.js:1243:15
at webdriver.promise.ControlFlow.runInNewFrame_ (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:1539:20)
at notify (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:362:12)
at notifyAll (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:331:7)
at resolve (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:309:7)
at fulfill (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:429:5)
at D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:1406:10
==== async task ====
WebDriver.executeScript()
at webdriver.WebDriver.schedule (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:268:15)
at webdriver.WebDriver.executeScript (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:404:15)
at D:\Git\mateserver\main.js:174:11
at D:\Git\mateserver\node_modules\selenium-webdriver\lib\goog\base.js:1243:15
at webdriver.promise.ControlFlow.runInNewFrame_ (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:1539:20)
at notify (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:362:12)
at notifyAll (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:331:7)
at resolve (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:309:7)
at fulfill (D:\Git\mateserver\node_modules\selenium-webdriver\lib\webdriver\promise.js:429:5)
Any thoughts on this? Am I using executeScript correctly? Thanks.
Update: It seems that if I put the get function inside the evalSelectAll function then it works. It seems as though passing functions as arguments to executeScript is not supported. Can anybody confirm this? It would be nice to have the code be more reusable by staying outside the eval function.

Is there a javascript serializer for JSON.Net?

I am using Newtonsoft JSON.Net to deserialize an object with PreserveReferencesHandling enabled. jQuery does not support relinking references based on the $ref and $id syntax JSON.Net uses (I don't know if jQuery supports this functionality in any capacity).
I tried using Douglas Crockford's cycle.js but that does not seem to work with my objects, the returned object is identical to the object which got passed in.
I am not incredibly familiar with JSON.Net, but I cannot seem to find any javascript libraries which would serialize (or parse) the JSON their .NET component outputs.
How can I accomplish putting back together object references?
I was looking for a solution to this problem as well, and ended up hacking Douglas Crockford's JSON.retrocycle function. His function does not work for the $ref=some number, but it looks for something like an xpath.
This is my quick and dirty version - don't use this as is - I'm not doing any cleanup, and it probably should be a plugin, but it does the job and is good enough to get going:
function retrocycle(o) {
var self = this;
self.identifiers = [];
self.refs = [];
self.rez = function (value) {
// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
path = item.$ref;
if (typeof path === 'string' && path != null) {
//self.refs[parseInt(path)] = {};
value[i] = self.identifiers[parseInt(path)]
} else {
self.identifiers[parseInt(item.$id)] = item;
self.rez(item);
}
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && path != null) {
//self.refs[parseInt(path)] = {};
value[name] = self.identifiers[parseInt(path)]
} else {
self.identifiers[parseInt(item.$id)] = item;
self.rez(item);
}
}
}
}
}
}
};
self.rez(o);
self.identifiers = [];
}
Use it like this:
$.post("url/function", { ID: params.ID }, function (data) {
retrocycle(data)
// data references should be fixed up now
}, "json");
You would have to write in a double look-up into your js parser. Technically preserving reference handling is to get around circular references, which is to say what would normally cause a stack overflow during parsing.
JSON does not have a native syntax for handling this. Newtonsoft version is a custom implementation, thus parsing the JSON will be a custom implementation.
If you really have to preserve such references, XML may be a better solution. There are some json->xml libraries out there.
Here is one solution for parsing that may be of use, or at least a guide:
https://blogs.oracle.com/sundararajan/entry/a_convention_for_circular_reference
This is my enhanced version of #Dimitri. #Dimitri code sometimes isn't able to rebuild the references. If anyone improves the code, please, tell me.
Regards,
Marco Alves.
if (typeof JSON.retrocycle !== 'function') {
JSON.retrocycle = function retrocycle(o) {
//debugger;
var self = this;
self.identifiers = [];
self.refs = [];
self.buildIdentifiers = function (value) {
//debugger;
if (!value || typeof value !== 'object') {
return;
}
var item;
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (var i = 0; i < value.length; i += 1) {
item = value[i];
if (!item || !item.$id || isNaN(item.$id)) {
if (item) {
self.buildIdentifiers(item);
}
continue;
}
self.identifiers[parseInt(item.$id)] = item;
self.buildIdentifiers(item);
}
return;
}
for (var name in value) {
if (typeof value[name] !== 'object') {
continue;
}
item = value[name];
if (!item || !item.$id || isNaN(item.$id)) {
if (item) {
self.buildIdentifiers(item);
}
continue;
}
self.identifiers[parseInt(item.$id)] = item;
self.buildIdentifiers(item);
}
};
self.rez = function (value) {
// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
if (item.$ref)
path = item.$ref;
if (typeof path === 'string' && path != null) {
//self.refs[parseInt(path)] = {};
value[i] = self.identifiers[parseInt(path)];
continue;
}
//self.identifiers[parseInt(item.$id)] = item;
self.rez(item);
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && path != null) {
//self.refs[parseInt(path)] = {};
value[name] = self.identifiers[parseInt(path)];
continue;
}
//self.identifiers[parseInt(item.$id)] = item;
self.rez(item);
}
}
}
}
}
};
self.buildIdentifiers(o);
self.rez(o);
self.identifiers = []; // Clears the array
};
}

Categories

Resources