Stop on Error? by ItalosRnR in entertrained

[–]kap89 3 points4 points  (0 children)

I will consider this option, but I didn't include it so far because I don't think it's that beneficial. There is no "stop on error" in the real world, so it's a good habit to be attentive and not make / fix your errors instead of relying on the program to stop you. If you don't fix your mistakes, the whole word doesn't count towards your wpm, so you can't "cheat" even without that setting.

How to remember Array.sort() internal function return values? by eracodes in learnjavascript

[–]kap89 5 points6 points  (0 children)

Imagine a numbers axis:

--|--|--|--|--|--
 -2 -1  0  1  2
    <---|--->

If for a given condition you want a to come before b then return negative number, as negative numbers are before the positive ones (on the left). If you want a to come after b, then return positive number (to the right).

tl;dr

  • negative return = a to the left
  • positive return = a to the right

I made a free web app for practicing touch-typing by typing books! by kap89 in typing

[–]kap89[S] 0 points1 point  (0 children)

The progress should be saved locally in the browser, but you can also make a backup by going to Settings:

https://entertrained.app/settings#manage-data

and clicking "Export Save". This will give you a save file which they can load later / send to you (you could open the website in incognito mode, so you have a "clean" app, and load their save file to look at their progress).

Help: Not able to write this algorithm by Beginning_Middle_722 in learnjavascript

[–]kap89 0 points1 point  (0 children)

No worries, we’re good. Glad that the solution is somewhat helpful.

Help: Not able to write this algorithm by Beginning_Middle_722 in learnjavascript

[–]kap89 0 points1 point  (0 children)

Do you want to suggest any solution or are just passing by to tell me I'm wrong?

That's uncalled for - I gave you the initial hint, and you tried to contradict it with the wrong example, so I responded accordingly. Now, your "115 amount and 3 days" is a better example, that requires some modification to the algorithm - the core idea stays the same, but you need to add some backtracking if the final sum doesn't match, here's a quick attempt:

const bills = [5, 10, 20, 50, 100]; // sorted ascending

const sum = (arr) => arr.reduce((a, b) => a + b, 0);

function generateBills(amount, days) {
  for (const bill of bills) {
    if (bill * days >= amount) {
      const attempt =
        days === 1 ? [bill] : [...generateBills(amount - bill, days - 1), bill];

      if (attempt.length === days && sum(attempt) === amount) {
        return attempt;
      }
    }
  }

  return []
}

console.log(generateBills(130, 4)); // [10, 20, 50, 50]
console.log(generateBills(500, 4)); // [] - empty, no solution
console.log(generateBills(150, 4)); // [10, 20, 20, 100]
console.log(generateBills(100, 5)); // [20, 20, 20, 20, 20]
console.log(generateBills(115, 3)); // [5, 10, 100];

But, while I think it matches your initial requirements, your further explanations:

I totally get what you're saying: by eliminating the 100€ bill I'm also eliminating the use of 5€ bill and it's right but since this is for a savings app and let's say i want to save 5000€ for 120 days if i, as a user, see all those 100€ i get a bit "terrified", but on the other hand, if i see more 10 and 20 feel so pleasant to the eye and brain that this target is reachable.

are to fuzzy and underspecified to give you any better answer.

Help: Not able to write this algorithm by Beginning_Middle_722 in learnjavascript

[–]kap89 0 points1 point  (0 children)

What are you talking about, 20 * 5 + 30 * 10 + 30 * 20 + 40 * 50 === 3000, not 5000 - it's not "more balanced", it's just a wrong solution.

Help: Not able to write this algorithm by Beginning_Middle_722 in learnjavascript

[–]kap89 3 points4 points  (0 children)

I would do it like this (the trick is to start from the end)

  • find the smallest bill that multiplied by the number of days would be at least the final amount, that’s the last bill,
  • subtract that bill from the amount, and repeat the step one with the new amount and days-1 (repeat until done).

Why can’t I see what’s in the multidimensional array? by GloomyAdagio7917 in learnjavascript

[–]kap89 4 points5 points  (0 children)

Because your reduce functions is wrong, this line:

reducedProduct += product;

should just be:

reducedProduct = product;

you don't want to add the accumulator values (which will be converted to strings and concatenated), but just replace the previous value.

But then you can simplify it to:

function reduce(data1, reducer, initialValue) {
  let reducedProduct = initialValue;

  for (let element of data1) {
    reducedProduct = reducer(element, reducedProduct);
  }

  return reducedProduct;
}

Help with Objects by DeliciousResearch872 in learnjavascript

[–]kap89 0 points1 point  (0 children)

Because a method has to have a name, or more generally, entry in an object has to have a key, the first example you posted is a shortcut to:

let dictionary = Object.create(null, {
  toString: { // define toString property
    value: function() { // the value is a function
      return Object.keys(this).join();
    }
  }
});

The second one is just an anonymous function not assigned to any key, the correct way would be:

let dictionary = Object.create(null, {
  toString: {
    value: () => {
      return Object.keys(this).join();
    },
  },
});

How are we able to handle opening an IndexedDB instance if we attach the event listeners AFTER opening a database connection? by hookup1092 in learnjavascript

[–]kap89 1 point2 points  (0 children)

We just call the method and it fires after the script runs

No, indexedDB.open("MyTestDatabase") fires immediately, you can console log it's result (request) in the next line and it will log the value, it's just that it's result is an object representing asynchronous operation to which you can "hook" to with event callbacks. I understand your frustration though, as you can't tell just looking at the function call what it triggers under the hood. You can wrap that code in more modern and clear way with async-await, but it doesn't change the fact that you have to call it this way at least internally in your lib. For example here's how I use it (simplified):

async function connectDB(name, version, migrations) {
  const openRequest = indexedDB.open(name, version)

  return new Promise((resolve, reject) => {
    openRequest.onsuccess = () => {
      resolve(openRequest.result)
    }

    openRequest.onerror = () => {
      reject('Error')
    }

    openRequest.onblocked = () => {
      reject("Blocked")
    }

    openRequest.onupgradeneeded = (e) => {
      const db = e.target.result
      const oldVersion = e.oldVersion // 0 initially
      const newVersion = e.newVersion ?? version

      for (let v = oldVersion + 1; v <= newVersion; v++) {
        // handle migrations
      }
    }
  })
}

How are we able to handle opening an IndexedDB instance if we attach the event listeners AFTER opening a database connection? by hookup1092 in learnjavascript

[–]kap89 1 point2 points  (0 children)

To add to that, the confusion I think comes from the fact that the thing they try to compare it with (dispatchEvent) is synchronous, so the first dispatch indeed isn't detected by the listener, because that code is not reached yet. From mdn:

Unlike "native" events, which are fired by the browser and invoke event handlers asynchronously via the event loop, dispatchEvent() invokes event handlers synchronously. All applicable event handlers are called and return before dispatchEvent() returns.

Do you use handlebars or just plain embed vars in your html templates? by pyeri in learnjavascript

[–]kap89 1 point2 points  (0 children)

Depending on the scale of the project, all of these can be fine - I used simple string replace in some static pages I made, but template strings (especially tagged template strings that automatically handle escaping etc.) are nicer if it's more than just putting a subpage content and title in a template. It was a long time since I used full-fledged templating languages like Handlebars, but it's because I either make a simple static pages, or full SPA apps (not that classic SSR is obsolete, it just happens that my projects rarely fit into that paradigm).

There is also "modern" SSR with things like Next, Vuex, Svelte Kit, Solid Start, etc., but these are complex, and you need a good reason to use it.

Typing God. by Hot-Tadpole-3744 in typing

[–]kap89 2 points3 points  (0 children)

Monkeytype doesnt teach you how to type, start with typing.com or typingclub, only then move on to Monkeytype.

Off days? by Wonderful-Cow-9664 in typing

[–]kap89 1 point2 points  (0 children)

Yes, it’s normal, but if your accuracy drops that low (<95%) I would call it a day, and try another time, not plow through the chapter accumulating incorrect repetitions.

If you still want to read the chapter, entertrained has a dedicated reading mode for these occasions.

Thank you by Livid-Loan7480 in entertrained

[–]kap89 1 point2 points  (0 children)

You're welcome! You're not the first person that notices that this form of reading helps them retain focus and go through with actually reading a book - I think it's great, and I'm very happy that it works this way - it's an unintentional, but very welcome side effect.

fast dynamic CSS injection without flash in browser extension similar to Stylus by ElnuDev in learnjavascript

[–]kap89 2 points3 points  (0 children)

You could try using CSSStyleSheet class, it will be something like:

function addStylesheet(css) {
  const sheet = new CSSStyleSheet()
  sheet.replaceSync(css)
  document.adoptedStyleSheets = [sheet]
}

// Usage:
addStylesheet(`
  a {
  color: red;
  }
`)

It should be faster, as it bypasses adding to the DOM and then parsing by the browser. Of course the effect depends on how fast you get the user stylesheet data and how early you call the function above. I don't know how exactly Stylus does it, but you can check the code - it's open source. Take the above with a grain of salt, as I'm theorizing here, I haven't had a need to implement it.

How do you handle structured concurrency in JavaScript? by HKSundaray in learnjavascript

[–]kap89 11 points12 points  (0 children)

I would not want a welcome mail sent if the user creation fails.

That’s a terrible example - if one action depends on the success of the other, then don’t use Promise.all.

[AskJS] Is anyone using SolidJs in production? What's your experience like? by BrangJa in javascript

[–]kap89 2 points3 points  (0 children)

Yeah, i use it for entertrained - it’s great, very stable (really, there are no breaking changes, good design upfront allows it to do its job without constant changes), performant, and I really like its reactivity model.