Why does this code log return false? - javascript

I can't figure out why this snippet logs false. I'm convinced it should log to true. What am I doing wrong?
var hasElb = function(string12b,char12b) {
var el = [];
for (var i = 0; i < string12b.length; i++ ) {
if (string12b[i] === char12b) {
el += char12b;
}
}
if (el[0] === char12b) {
console.log(true + " el[0] = " + el[0] + " and char12b = " + char12b);
}
else {
console.log(false + " el[0] = " + el[0] + " and char12b = " + char12b);
}
};
hasElb([1,3,5,7,9,11],7);

To add an element to an array, you use .push(), not +=:
if (string12b[i] === char12b) {
el.push(char12b);
}

Related

Object.defineProperty called on non-object error

I have this error in jQuery about this code .. and i can't fix it .. i don't understand it and the console log ...
Code is a notifications tool in Blogger that runs cookies
Object.defineProperty called on non-object .... at Function.defineProperty ()
$(function() {
var view = settingsnoti["noti-bloghomepageUrl"];
var message = void 0 !== settingsnoti["word"] ? settingsnoti["word"] : "";
var _0x322dc6 = false !== settingsnoti["allow-noti"];
var a_second = void 0 !== settingsnoti.expires ? settingsnoti.expires : 7;
var _0x48e20c = void 0 !== settingsnoti["color"] ? settingsnoti["color"] : "#388d80";
var styleFloat = void 0 !== settingsnoti.float ? settingsnoti.float : "right";
var lessFileName = false !== settingsnoti["ltr"];
language_form = "" !== message ? message : ["تحديد الكل كمقروء", "قبول", "إلغاء", "عرض", "زيارة", "إشعار", "إعلان", "تحديث", "راجع مالجديد!!"];
var load = function(_height) {
return language_form[parseInt(_height - 1)];
};
switch (lessFileName) {
case true:
badge_dir = "ltr-badge";
break;
case false:
default:
badge_dir = "rtl-badge";
}! function($) {
var abbr;
var i = "#notification-badge";
var element = 'input[name="badge[]"]';
var value = "#notibadgeBtn";
$.fn.ihavebadge = function(name, all) {
var map_el = $(this);
var item = $.extend({
"childTypes": settingsnoti,
"delay": 1,
"expires": a_second,
"onAccept": function() {},
"ImageSize": 116,
"substring": 140,
"float": styleFloat,
"ltr": lessFileName,
"bloggcodeNAM": "PicFast",
"bloggcodeURI": "https://blogg-code.blogspot.com",
"macrosid": "AKfycbykx1ZVe0t0qmw4sZ2Pez4iYNFXnv8w6HAANNtXs5VCX38RS_A",
"noImage": "https://3.bp.blogspot.com/-7CnHTs2OKS8/Wo214lKp0KI/AAAAAAAACPk/CD1mAZz7IwI32hkGM3aVbD6Tefw78IkvgCLcBGAs/s72/no-img-300x300-blogg-code.jpg",
"Imgavatar": "https://1.bp.blogspot.com/-mP-2bvOaWuM/XAkrMTFABaI/AAAAAAAADjU/tqSHDVesLcYwQ1rXt1MVvG3TENbJqMvcQCLcBGAs/s72/no-user.png",
"Monthformat": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
}, name);
var types = {
"getstyle": function(p) {
$(p).appendTo($("head"));
},
"b": function(context, data, res, a, f, cb) {
context.prop("checked", cb);
context.attr("data-auto", data).parent().css({
"background-color": res,
"opacity": a,
"pointer-events": f
});
},
"getlocation": function(index) {
if (index) {
setInterval(function() {
window.location.href = index;
}, 2E3);
}
},
"getcopyright": function(delete_behavior_form) {
var artistTrack = '<li class="notirights px ads badg_radius5 styleimpo"><label class="notirights">' + load(7) + ':</label><span class="notirights type">' + item.bloggcodeNAM + '</span><span class="notirights ilink"><a class="notirights badgehover-opa badg_radius30" href="' + item.bloggcodeURI + '" target="_blank">' + load(5) + "</a></span></li>";
if (0 !== $(".notirights").length) {
$(".notirights").each(function() {
if (($(this).css("opacity") < 1 || "hidden" == $(this).css("visibility") || $(this).is(":hidden")) && $(i).is(":visible")) {
types.getlocation(item.bloggcodeURI);
}
});
} else {
$(delete_behavior_form).prepend(artistTrack);
}
}
};
types.getstyle("<style type='text/css'>div#notification-badge .button,div#notification-badge ul li label,#notification-badge input[type=checkbox],div#notification-badge .badgehover-var:hover {color:" + _0x48e20c + ";}div#notification-badge .button.done,#notification-badge input[type=checkbox]:checked::before,div#notification-badge .ilink a {background-color:" + _0x48e20c + ";}div#notification-badge .button.done,div#notification-badge .button.cancel:hover {border: 1px solid " + _0x48e20c + ";}div#notification-badge .styleimpo {display:block!important;opacity:1!important;visibility:visible!important;width:auto!important;height:auto!important;padding:5px!important;background-color:#ffffff!important;border:1px solid" + _0x48e20c + "!important}</style>");
var pix_color = "";
Math.floor(+Math["random"]() + 1);
if ($("body").hasClass("Preview")) {
var retryLinkHref = view.replace(/\/$/, "");
} else {
retryLinkHref = window.location.origin;
}
var requestOrUrl = retryLinkHref.toLowerCase() + "/feeds/posts/default?alt=json-in-script&orderby=updated&start-index=1&max-results=1";
$.ajax({
"url": requestOrUrl,
"dataType": "jsonp",
"type": "GET",
"success": function(xhr, status, custom) {
if ("entry" in xhr.feed) {
var i = 0;
for (; i < xhr.feed.entry.length; i++) {
var data = xhr.feed.entry[i];
var version = 0;
for (; version < data.link.length; version++) {
var result = data.link[version];
if ("replies" == (result = data.link[version]).rel && "text/html" == result.type) {
result.title;
result.href;
}
if ("alternate" == result.rel) {
var replacements = result.href;
if (-1 !== replacements.indexOf(".blogspot.")) {
replacements = replacements.replace("http://", "https://");
}
break;
}
}
var word = item.Monthformat;
var nickname = data.updated.$t;
var _0x4afe5a = nickname.substring(0, 10);
var contentId = _0x4afe5a.substring(0, 4);
var cPointX = _0x4afe5a.substring(5, 7);
var linkCssId = _0x4afe5a.substring(8, 10) + "-" + word[parseInt(cPointX - 1)] + "-" + contentId;
var _0x417c4f = (data.published.$t.substr(0, 10).replace(/\-/g, "_"), data.title.$t);
var height = item.Imgavatar;
if (void 0 !== data.author[0].uri) {
var value = data.author[0].name.$t;
if (data.author[0].gd$image.src.match("blogblog")) {
var whatToScale = height;
} else {
whatToScale = data.author[0].gd$image.src;
}
var heightInCells = whatToScale.replace(/http:\/\//, "https://").replace("/72-c/", "/s220/");
var id = data.author[0].uri.$t;
} else {
value = "Unknown";
heightInCells = height;
id = "javascript:void(0)";
}
if (void 0 !== data.media$thumbnail) {
var entryOrArray = data.media$thumbnail.url;
var id = item.ImageSize;
var timestamp = entryOrArray.replace(/http:\/\//, "https://").replace("/s72-c/", "/s" + id + "/").replace("?imgmax=800", "");
} else {
if (void 0 !== data.content && null != data.content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/)) {
var shapePathsCollection = data.content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/).pop();
if (11 == shapePathsCollection.length) {
timestamp = "//img.youtube.com/vi/" + shapePathsCollection + "/0.jpg";
}
} else {
if (void 0 !== data.content && null != data.content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)) {
timestamp = data.content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
} else {
timestamp = item.noImage;
}
}
}
if (void 0 !== data.summary) {
var matches = data.summary.$t.replace(/<\S[^>]*>/g, "");
var resizewidth = matches.substring(0, item.substring) + "...";
if (300 < matches.length) {
matches.substring(0, 170);
}
if (100 < matches.length) {
matches.substring(0, 100);
}
} else {
if (void 0 !== data.content) {
var result = data.content.$t.replace(/(<([^>]+)>)/gi, "");
resizewidth = result.substring(0, item.substring) + "...";
if (300 < result.length) {
result.substring(0, 170);
}
if (100 < result.length) {
result.substring(0, 100);
}
} else {
resizewidth = "";
}
}
var _0xb2707 = data.id.$t.split(".post-").pop();
pix_color = pix_color + ('<li class="px badg_radius5"><input type="checkbox" id="badge-id-cookietypeupdated-' + _0xb2707 + '" name="badge[]" value="updated-' + _0xb2707 + '" data-auto="off"/><label for="badge-id-cookietypeupdated-' + _0xb2707 + '">' + load(8) + ':</label>' + load(9) + '<abbr class="timeago idate badg_radius30" title="' + nickname + '">' + linkCssId + '</abbr><span class="icontent"><a class="badgehover-var" href="' + replacements + '" target="_blank"><img class="badg_radius5" src="' + timestamp + '"/>' + _0x417c4f + '</a></span><span class="inameauthor"><a class="badgehover-var" href="' + id + '" target="_blank" rel="nofollow"><img class="badg_radius100" src="' + heightInCells + '"/><i class="authorname">' + value + '</i></a></span></li>');
}
}
var isScaytNode = clone("badgeControl");
var workspace = clone("badgeControlPrefs");
if (isScaytNode && workspace && "reinit" != all) {
var item2 = true;
if (false == isScaytNode) {
item2 = false;
}
filter(item2, item.expires, i);
} else {
$(i).remove();
var summaryHtml = "";
preferences = JSON.parse(workspace);
$.each(item.childTypes, function(canCreateDiscussions, url) {
if ("" !== url.type && "" !== url.value && "" !== url.link && url.type) {
var th_field = "";
if (false !== url.link) {
th_field = '<span class="ilink"><a class="badgehover-opa badg_radius30" href="' + url.link + '" target="_blank">' + load(4) + '</a></span>';
}
summaryHtml = summaryHtml + ('<li class="px badg_radius5"><input type="checkbox" id="badge-id-cookietype' + url.value + '" name="badge[]" value="' + url.value + '" data-auto="off"/><label for="badge-id-cookietype' + url.value + '">' + load(6) + ':</label><span class="type">' + url.type + '</span>' + th_field + '</li>');
}
});
var artistTrack = '<div id="notification-badge" class="' + badge_dir + 'badg_shadowkit badg_radius2" style="display: none;"><div id="badge-types"><p><button class="button btn-top select" id="badge-btn-select" type="button">' + load(1) + '</button></p><ul>' + summaryHtml + pix_color + '</ul></div><p><button class="button btn-bottom done badgehover-opa badg_radius5" id="badge-btn-done" type="button">' + load(2) + '</button><button class="button btn-bottom cancel badg_radius5" id="badge-btn-cancel" type="button">' + load(3) + '</button></p></div>';
$(map_el).append(artistTrack);
setTimeout(function() {
$.each(preferences, function(canCreateDiscussions, domRootID) {
if (1 != $('#badge-id-cookietype' + domRootID).length) {
abbr = $('#badge-id-cookietype' + domRootID).length;
}
});
var d = preferences.length;
var v = $(element).length;
var m = v - d;
if (0 == abbr && (m = v - d + 1), d || (m = v), 10 < m && (m = "+9"), 0 < m) {
var artistTrack = '<span class="' + badge_dir + 'badge alert badg_radius100">' + m + '</span>';
$(value).append(artistTrack).addClass("Animat-notifications");
}
}, item.delay);
$(window).scroll(function() {
fn(i, value);
});
$("body").on("click", value, function() {
if ($(i).is(":hidden")) {
$(i).hide(function() {
$(".badge").remove();
$(value).addClass("active").removeClass("Animat-notifications");
var x;
var orig_top = $(value).offset().top + $(value).height();
if ("left" === item.float) {
x = $(value).offset().left;
$(this).css({
"top": orig_top + "px",
"left": x + "px"
});
} else {
if ("right" === item.float) {
x = $(window).width() - ($(value).offset().left + $(value).outerWidth());
$(this).css({
"top": orig_top + "px",
"right": x + "px"
});
}
}
$.each(preferences, function(canCreateDiscussions, conid) {
if ($.fn.ihavebadge.preference(conid)) {
types.b($("#badge-id-cookietype" + conid), "on", "white", ".4", "none", true);
}
});
}).fadeIn(100);
}
types.getcopyright("#notification-badge ul");
});
$(i).click(function(canCreateDiscussions) {
if ("BUTTON" !== canCreateDiscussions.target.nodeName) {
canCreateDiscussions.stopPropagation();
}
});
$(element).on("change", function() {
if (this.checked) {
types.b($(this), "on", "white", ".4", "auto");
} else {
types.b($(this), "off", "#f8f8f8", "1", "auto");
}
});
$("body").on("click", "#badge-btn-select", function() {
types.b($(element), "on", "white", ".4", "auto", true);
$("#badge-btn-done").trigger("click");
});
$("body").on("click", "#badge-btn-cancel", function() {
fn(i, value);
});
$("body").on("click", "#badge-btn-advanced", function() {
types.b($(element), "off", "#f1f1f1", "1", "auto", false);
});
$("body").on("click", "#badge-btn-done", function() {
filter(true, item.expires, i);
var data = [];
$.each($(element).serializeArray(), function(canCreateDiscussions, nodes) {
data.push(nodes.value);
var item = '#badge-id-cookietype' + nodes.value;
types.b($(item), "on", "white", ".4", "none");
});
trigger("badgeControlPrefs", JSON.stringify(data), 365);
item.onAccept.call(this);
});
}
}
});
};
$.fn.ihavebadge.cookie = function() {
var message = clone("badgeControlPrefs");
return JSON.parse(message);
};
$.fn.ihavebadge.preference = function(_relatedTarget) {
var currentLineStylesCloned = clone("badgeControl");
var data = clone("badgeControlPrefs");
return data = JSON.parse(data), false !== currentLineStylesCloned && (false !== data && -1 !== data.indexOf(_relatedTarget));
};
var filter = function(key, val, enhanced) {
trigger("badgeControl", key, val);
$(enhanced).fadeOut("fast", function() {
fn(this, value);
});
};
var fn = function(id, el) {
$(id).removeAttr("style");
$(el).removeClass("active");
};
var trigger = function(y, x, keys) {
var expected_date2 = new Date;
expected_date2.setTime(expected_date2.getTime() + 24 * keys * 60 * 60 * 1E3);
var _0x491ad2 = "expires=" + expected_date2.toUTCString();
return document.cookie = y + "=" + x + ";" + _0x491ad2 + ";path=/", clone(y);
};
var clone = function(method) {
var data = method + "=";
var PL$13 = decodeURIComponent(document.cookie).split(";");
var PL$17 = 0;
for (; PL$17 < PL$13.length; PL$17++) {
var PL$6 = PL$13[PL$17];
for (;
" " == PL$6.charAt(0);) {
PL$6 = PL$6.substring(1);
}
if (0 === PL$6.indexOf(data)) {
return PL$6.substring(data.length, PL$6.length);
}
}
return false;
};
}(jQuery);
var am_Overlay = {
"onAccept": function() {
console.log("%cnotification saved...", "color:tomato");
}
};
if (true == _0x322dc6) {
$("body").ihavebadge(am_Overlay, "reinit");
} else {
$("#notibadgeBtn").remove();
}
});
how i can fixed it i want to help please .. and thanks you for all :)

Object.keys(arr).reduce() returns undefined

I am creating an object from an array like so
var val = $(this).val();
var type = " " + $("#backing").val() + " ";
var arr = $.extend({}, comb_arr[type]);
The result
var arr = {"1-4 ": "$10.10 ", "5-9 ": "$8.34 ", "10-24 ": "$7.71 ", "25-49 ": "$7.21 "}
When I run the below code through the output is undefined
var price = Object.keys(arr).reduce((a, c) => {
var s = c.trim();
if(/\d+\-\d+/.test(s)){
var range = s.split("-");
if(val >= parseInt(range[0]) && val <= parseInt(range[1])){
a = comb_arr[c];
}
}else{
s = s.replace(/\D/g, "");
if(val >= s){
a = comb_arr[c];
}
}
return a;
},0);
All ideas are welcome!

Code studio javascript

So I'm basically making an savings account system. A user can set up an account and start with a balance of 0 the withdraw and deposit money whenever they want. It works perfectly the first few times but then it gives me the RangeError either when I try logging in or out.
setScreen('LogIn');
var balance;
var curbal = [];
var totalAccts=[];
onEvent("saveAcct", "click", function() {
var username = getText('createUserInput');
var password = getText('createPassInput');
appendItem(totalAccts, getText('createUserInput') + " " +
getText('createPassInput') + " ");
console.log("Username: " + username + " Password: " + password);
console.log(totalAccts);
setScreen('LogIn');
});
onEvent('makeAcct', 'click', function(){
setScreen('CreateAcct');
setText('createUserInput', "");
setText('createPassInput', "");
setText("userInput", "");
setText("passInput", "");
hideElement('alert');
});
onEvent('addMoney', 'click', function(){
setNumber('balance', balance + getNumber('addInput'));
balance = balance + getNumber('addInput');
setNumber('addInput', '');
console.log(balance);
});
onEvent('subMoney', 'click', function(){
setNumber('balance', balance - getNumber('subInput'));
balance = balance - getNumber('subInput');
setNumber('subInput', '');
console.log(balance);
});
onEvent('login', 'click', function(){
balance = 0;
changeEnBal(totalAccts, curbal);
});
onEvent('logout', 'click', function(){
changeExBal(totalAccts, getNumber('balance'), curbal);
hideElement('alert');
setText('balance', 0);
setText("userInput", "");
setText("passInput", "");
setScreen('LogIn');
});
onEvent("goBack", "click", function() {
setScreen('LogIn');
});
function changeEnBal(list, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
setScreen('Account');
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balance = balList[a];
setNumber('balance', balList[a]);
setScreen('Account');
console.log(balList[a]);
}
}
}
}
for (var b = 0; b < balList.length; b++) {
if (balList[b] != (user + " " + pass + " " + balList[b])){
showElement('alert');
}
}
}
function changeExBal(list, curBal, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
list[i] = user + " " + pass + " " + curBal;
appendItem(curbal, curBal);
console.log(curbal);
console.log(list[i]);
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balList[a] = curbal;
list[i] = user + " " + pass + " " + curBal;
}
}
}
}
console.log(totalAccts);
}
As suggested in some of the comments I would change your for loops to start with a zero index:
for (var i = 0; i < list.length; i++)
and
for (var a = 0; a < balList.length; a++)

javascript-why only partial code is executed

In the below code, initially as the page is loading, complete block is executed. But after the page is loaded, only the else condition is getting executed.why?
Please find below complete piece of code.
unction verifyrequestArray(id) {
console.log("in verifyrequestarray" + requestArray.length);
var y = true;
//requestArray=["1012-abc","2089-xyz","1012-abc"];
var tempArr = [];
//for removing duplicates in the array
for (i = 0; i < requestArray.length; i++) {
if (tempArr.indexOf(requestArray[i]) == -1) {
tempArr.push(requestArray[i]);
}
}
//alert(tempArr);
//verify if the value already exists
for (j = 0; j < tempArr.length; j++) {
if (tempArr.hasOwnProperty(id)) {
console.log("req id already present in array");
break;
} else {
console.log("req id not present in array");
return false;
}
}
}
function getStatusfromArray(id) {
console.log("in get status");
requestStatus = requestArray.hasOwnProperty(id);
console.log("status for " + id + ":" + requestStatus);
return requestStatus;
}
function setTooltip(currentTag, status) {
console.log("in settooltip" + currentTag);
currentTag.attr("title", status); //setting status a tooltip
}
function getStatusUsingAjax(requestValue, callback) {
console.log("inside function getStatusUsingAjax");
var currentStatus;
GM_xmlhttpRequest({
method: "GET",
url: link,
async: false,
onload: function(response) {
if ($(response.responseText).find("#P16_STATUS2").size() === 1) {
currentStatus = $(response.responseText).find("#P16_STATUS2").text();
console.log("Status is " + currentStatus);
} else if ($(response.responseText).find("#P16_STATUS3").size() === 1) {
currentStatus = $(response.responseText).find("#P16_STATUS3").val();
console.log("Status is " + currentStatus);
}
var pusharr2 = [requestValue + "-" + currentStatus];
requestArray.push(pusharr2);
//console.log("Updated Array is "+requestArray);
callback(currentStatus);
}
});
}
function loadStatus(x) {
$('.a-IRR-table tr').each(function(i) {
var val = $(this).find("td").eq(0).text();
if ((val !== "-") && (val !== "")) {
link = $(this).find("td").eq(0).find("a").attr("href");
linkTag = $(this).find("td").eq(0).find("a");
console.log("Link Tag is " + linkTag);
console.log("val is " + val);
var x = verifyrequestArray(val);
console.log("x is " + x);
if (verifyrequestArray(val)) {
var updatedStatus = getStatusfromArray(val);
setTooltip(linkTag, updatedStatus);
} else {
console.log("in else");
//var updatedStatus2=getStatusUsingAjax(val);
getStatusUsingAjax(val, function(updatedStatus2) {
console.log("UpdatedStatus2 is " + updatedStatus2);
console.log("Link Tag is " + linkTag);
setTooltip(linkTag, updatedStatus2);
});
sleep(1.5 * 1000);
}
}
});
}

dynamically build a hierarchical dojo tree menu

I want to build a hierarchical dojo tree menu with folders and sub-folders from this html file:
<div id="prelude"><h2>Prélude</h2></div>
<div id="_BaseTestsAsync_00_NUnitIsWorking_Passed">_BaseTestsAsync_00_NUnitIsWorking<br/>Yo!</div>
<div id="_BaseTestsAsync_01_TwincatisRunning_Passed"><h2><font color="darkgreen">_BaseTestsAsync_01_TwincatisRunning</font></h2></div>
<div id="_BaseTestsAsync_02_CorrectPLCModuleIsActive_Passed">_BaseTestsAsync_02_CorrectPLCModuleIsActive</div>
<div id="AsynchronousTests_read1600OutsideRange_Passed"><h2>AsynchronousTests_read1600OutsideRange</h2></div>
<div id="AsynchronousTests_readNonEmpty1600_1_Passed"><h2>AsynchronousTests_readNonEmpty1600_1</h2></div>
<div id="AsynchronousTests_readUnknownRegister_Passed">AsynchronousTests_readUnknownRegister</div>
<div id="Robustness_WriteCurrentPosition_Passed"><h2><font color="darkgreen">Robustness_WriteCurrentPosition</font></h2></div>
<div id="Robustness_WriteIllegalSpeedPosition_Passed">Robustness_WriteIllegalSpeedPosition</div>
require([
"dojo/_base/declare", "dojo/_base/window", "dojo/store/Memory", "dijit/tree/ObjectStoreModel", "dijit/Tree", "dojo/domReady!"
], function (declare, win, Memory, ObjectStoreModel, Tree) {
divs = document.getElementsByTagName("DIV");
s = ""
var adivs = Array.prototype.slice.call(divs);
function rootName(name, depth) {
var lpath = name.split("_")
var limit = 0
if (lpath.length > depth) {
limit = depth
} else {
limit = lpath.length
}
var s = ""
for (m = 0; m < limit; m++) {
s = s + lpath[m] + "_"
}
//console.log("3[n: " + name + "][d: " + depth + "][lp: " + lpath + "][li: " + limit + "]->[s: " + s + "]")
return s
}
function hierarchy(arr, depth, parent) {
var s = ""
var arr2 = arr.map(function (a) {
var lpath = a.id.split("_")
var atdepth = ""
if (lpath.length > depth) {
atdepth = lpath[depth]
}
//console.log(" ***arr2[d: " + depth + "][parent: " + parent + "][ad: " + atdepth + "][id: " + a.id + "]")
return [a, atdepth]
});
var groups = {};
arr2.map(function (a) {
if (a[1] in groups) groups[a[1]].push(a[0]);
else {
groups[a[1]] = [];
groups[a[1]].push(a[0])
}
});
for (key in groups) {
//console.log(" ----groups[d: " + depth + "][k: " + key + "][gk: " + groups[key] + "][parent: " + parent + "]")
if (groups[key] === undefined) {} else {
if (groups[key].length == 1) {
var label = ""
var id = groups[key][0].id
if (id.indexOf("ailed") >= 0) {
label = "<b><font color=red>" + id + "</font></b>"
} else {
label = "<font color=darkgreen>" + id + "</font>"
}
var z = "1[d: " + depth + "][k: " + key + "][lbl: " + label + "][parent: " + parent + "], "
s = s + z
store3.put({
"id": id,
"label": label,
"type": "test",
"parent": parent
})
//console.log(" -l1-groups " + z)
} else {
var id = groups[key][0].id
var branchname = rootName(id, depth + 1)
var menuEntry = "<br/>2[d: " + depth + "][z: " + z + "][parent: " + parent + "][k: " + key + "][gkl: " + groups[key].length + "][p: " + branchname + "], "
var below = hierarchy(groups[key], depth + 1, rootName(id, depth + 1))
s = s + menuEntry + below
store3.put({
"id": branchname,
"label": branchname,
"type": "title",
"parent": parent
})
//console.log(" -l2-groups " + menuEntry)
}
}
}
return s
}
var store3 = new Memory({
data: [{
"id": "world",
"label": "Tests",
"type": "title"
}],
getChildren: function (object) {
return this.query({
parent: object.id
});
}
})
hierarchy(adivs, 0, "world");
// Create the model
var myModel = new ObjectStoreModel({
store: store3,
query: {
id: 'world'
},
labelAttr: "label"
});
// Custom TreeNode class (based on dijit.TreeNode) that allows rich text labels
var MyTreeNode = declare(Tree._TreeNode, {
_setLabelAttr: {
node: "labelNode",
type: "innerHTML"
}
});
// Create the Tree.
var tree = new Tree({
model: myModel,
_createTreeNode: function (args) {
return new MyTreeNode(args);
},
onClick: function (item) {
console.log("menuItem1: " + item.id)
menuItem = item.id
if (menuItem.length > 0) {
divtest = document.getElementById(menuItem);
divs = document.getElementsByTagName("DIV");
if (divtest != null) {
for (i = 0; i < divs.length; i++) {
if (divs[i].id.length == 0) {} else if (divs[i].id.indexOf("dijit") == 0) {} else if (divs[i].id.indexOf("mytree") == 0) {} else {
divs[i].style.display = "none";
}
}
divtest.style.display = "block";
menuItem = "#" + menuItem
} else {
for (i = 0; i < divs.length; i++) {
if (divs[i].id.length > 1) {
if (divs[i].id.indexOf(menuItem) == 0) {
divs[i].style.display = "block";
} else if (divs[i].id.indexOf("dijit") == 0) {
divs[i].style.display = "block";
} else {
divs[i].style.display = "none";
}
} else {
divs[i].style.display = "block";
}
}
menuItem = ""
}
}
}
});
tree.placeAt(win.body(), "first");
tree.startup();
});

Categories