Reputation: 845
var roots = [], children = {};
// find the top level nodes and hash the children based on parents
for (var i = 0, len = arry.length; i < len; ++i) {
var item = arry[i],
p = item.Parent,
target = !p ? roots : (children[p] || (children[p] = []));
// I am not able to understand this line what it does
// target = !p ? roots : (children[p] || (children[p] = []));
target.push({ value: item });
}
what I understand that if p is null then childrens for that parent should be empty but why then need to use of || expression that is used in this code
(children[p] || (children[p] = [])
Upvotes: -1
Views: 104
Reputation: 4116
target = !p ? x : y
means if not p
then target = x
. Else target = y
(children[p] = [])
means assign an empty array to children[p]
(children[p] || (children[p] = []))
means if children[p]
is not null then return that. Else assign an empty array to children[p]
then return itp is null or undefined
=> target = roots
children[p] is NOT null
then target = children[p]
children[p] = []
then target = children[p]
which is an empty arrayif (!p) {
target = roots;
} else if (children[p]) {
target = children[p];
} else {
children[p] = [];
target = children[p];
}
Upvotes: 3
Reputation: 12152
|| is the Logical OR operator or the Conditional operator.It returns the first or second operand depending on whether the first is truthy or falsey. A truthy value means anything other than 0, undefined, null, "", or false.
This root:(children[p] || (children[p] = [])
means that if children[p]
is truthy then root is children[p]
else root will be children[p]=[]
. children[p]
will be assigned an empty array rather than a falsey value
Upvotes: 2
Reputation: 12854
If children[p]
is not defined (or this value is false, undefined, null, 0...), is setting with an new array.
The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
e.i.
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Upvotes: 1
Reputation: 67
There is a ternary operator to check if p
is not the item of parent then set the target to children and p elements array otherwise set to new empty array.
Upvotes: 0
Reputation: 490143
It is a more terse way to describe...
if (!children[p]) {
children[p] = [];
}
Upvotes: 1
Reputation: 386520
It is a conditional (ternary) operator ?:
with an inverted check of p
, which is the parent.
If p
not exists, then take roots
, otherwise take children of the parent or assign an empty array to it, as default value, and take it.
target = !p // condition
? roots // true part
: (children[p] || (children[p] = [])); // else part
Upvotes: 1