1

This code counts the number of links in a page:

let temp = {}
for (const page of pages) { 
    let count = temp[page.outgoingLinks.length];
    if (!count) {
        count = 0;
    } 
        count++;
    
    temp[page.outgoingLinks.length]=count;
}

I would like to avoid the need for the if check that initializes the value.

In this example, the default value is an integer. But I would like to store even an Array there, something like defaultdict in python. How can I do it in JS?

0

3 Answers 3

3

There is nothing like Python's defaultdict in JavaScript, however you can have a default value when accessing the property by using the nullish-coalescing operator:

let count = temp[page.outgoingLinks.length] ?? 0;
Sign up to request clarification or add additional context in comments.

2 Comments

You can alternatively compress it into temp[page.outgoingLinks.length] ??= 0; temp[page.outgoingLinks.length]++.
@Amadan Sure, you can get rid of the count variable and use temp[page.outgoingLinks.length] = (temp[page.outgoingLinks.length] ?? 0) + 1;
2

To avoid the need for the if check that initializes the value

for (const page of pages) { 
   temp[page.outgoingLinks.length] = temp[page.outgoingLinks.length] ? temp[page.outgoingLinks.length]++ : 0;
}

here you can direclty use ternary operator to do so.

Comments

1

As you want multiple default values, you could create an object that contains the default values. This object can be defined in a helper function that takes an argument which specifies the type of default value you want and returns a function that can be called with the value.

If that value is undefined or null, this function returns the required type of default value.

function getInitializer(typeOfDefault) {
  const defaults = {
    arr: [0, 0, 0],
    num: 0,
    emptyString: ''
  };

  return (value) => value ?? defaults[typeOfDefault];
}

// default number
const initialize = getInitializer('num');
const a = initialize(0);
console.log(a);

// default array
const initialize2 = getInitializer('arr');
const b = initialize2(null);
console.log(b);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.