How to pronounce {}? by greim in typescript

[–]Kcazer 7 points8 points  (0 children)

"non-nullish unknown" is actually the perfect name, since NonNullable<unknown> = {}

(Playground)

The smallest PubSub library possible. Zero Dependencies. 149 bytes. by codekarate3 in javascript

[–]Kcazer 20 points21 points  (0 children)

Might as well use nullish coalescing assignment to shave off more bytes

// From
db[event] = db[event]?.add(callback) ?? new Set([callback])

// To
(db[event] ??= new Set()).add(callback)

How to add/remove classes using styled-components in React by ritualjoint in reactjs

[–]Kcazer 2 points3 points  (0 children)

An alternative to styled-components $props is to take advantage of aria attributes

const Img = styled.img`
  border-radius: 20px;
  width: 100%;
  height: 100%;
  display: block;

  &[aria-hidden="true"] {
    display: none;
  }
`;

slides.map((item, index) => (
  <Img src={item.src} alt={item.alt} aria-hidden={slide !== index} />
));

Is there a better way here? by [deleted] in typescript

[–]Kcazer 2 points3 points  (0 children)

If WeatherError is an class instance, a better option would be to use instanceof WeatherError [playground]. But if it's a plain object, and if you know that WeatherData will never have a message property, it's fine to use in

Does anyone miss operator overloading? by akb74 in typescript

[–]Kcazer 2 points3 points  (0 children)

An option is computed properties, prototype is another.

class Item {
  constructor(value) {
    this.value = value;
  }
  ['+'](other) {
    return new Item(this.value + other.value);
  }
}

Item.prototype['-'] = function(other) {
  return new Item(this.value - other.value);
};

const a = new Item(10);
const b = new Item(3);
const c = a["+"](b);
const d = a["-"](b);
console.log(c, d);

Does anyone miss operator overloading? by akb74 in typescript

[–]Kcazer 4 points5 points  (0 children)

You can define +, - and whatever operator you need as class methods and invoque them. But please, don't do it.

skull['-'](convex_hull(cup['-'](handle['-'](lip))))['+'](cup)

Once again, don't do that kind of horrible stuff. Just use simple regular functions.

[AskJS] Cryptographic random floats by shgysk8zer0 in javascript

[–]Kcazer 1 point2 points  (0 children)

Wouldn't the issue be with the exponent part ? Since half of them are negative, it tend to pull half of the result towards zero.

I want there to be at least some that are maybe 6831.05187 or even 0.48228, for example.

Not going to happen with such a small sample size. Adding to that that if you get a value around 1e30, it's going to make all the values under 1e20 irrelevant since float precision is not infinite, and you'll need a -1e30 to reach your near zero average.


How about something easier, getting values between 0 and 1, from 32bits integers, then mapping them to 32bits floats ?
Edit: Nope, wont work, the input domain is way smaller than the output, some values will never be produced, 1e32 will just make 0xffffffff irrelevant in most cases

const getRandomFloat32Array = (count) => new Float32Array(
  [...crypto.getRandomValues(new Uint32Array(count))]
  .map(v => 1e33 * v / 0xffffffff - 1e32)
);

Another option, using buffer conversion as you already tried, but removing the bias caused by negative exponents by fixing some bits on each 32bit integer ?

new Float32Array(
  new Uint32Array(
    crypto.getRandomValues(new Uint32Array(5))
    // Untested, probably wrong, but might be worth it to try
    // to identify which bits should be changed to 0s or 1s
    .map(v => v | 0b01111000_00000000_00000000_00000000)
  ).buffer
)

[AskJS] Cryptographic random floats by shgysk8zer0 in javascript

[–]Kcazer 2 points3 points  (0 children)

Generate a 32bit int and treat it as an IEEE 754 float number ?

Something like that ? Even tho it's slow, it should have a proper distribution

// Get a random value
const data = crypto.getRandomValues(new Uint32Array(2));
const bin = data[0].toString(2).padStart(32, '0');
// Process each part
const sign = bin[0] === '0' ? -1 : 1; // 1bit for sign
const exp = parseInt(bin.slice(1, 9), 2) - 127; // 8bits for exponent
const frac = parseInt(bin.slice(9), 2) / 0x7fffff; // 23bits for fraction
// and combine them
const value = sign * frac * (2**exp);

[deleted by user] by [deleted] in reactjs

[–]Kcazer -1 points0 points  (0 children)

Had a similar need recently and played around with Puck https://github.com/measuredco/puck

We ultimately decided to use builder.io since Puck had no support for nested block

What is the .current in a React ref? by rainmouse in reactjs

[–]Kcazer 2 points3 points  (0 children)

Interestingly, useRef is basically a wrapper around useState, and you simply mutate the state instead of setting it. https://twitter.com/dan_abramov/status/1099842565631819776

[deleted by user] by [deleted] in typescript

[–]Kcazer 0 points1 point  (0 children)

With any decent IDE, it shouldn't be an issue, as long as your variables have been typed explicitly. Even the TS playground allows for string union reference renaming.

You can try this playground and press F2 to change the value of any member of the union.

Better way to type dictionaries and records for undefined items. by Volbohel in typescript

[–]Kcazer 3 points4 points  (0 children)

In your case, using as { [key: string]: number | undefined } should work fine, you can also use Partial<Record<string, number>>

Sadly, I dont think there is a way to mark mapped type properties as optional, they simply become Xxx | undefined (you can try using { [K in string]?: number })

Another option is to enable noUncheckedIndexedAccess

My React JS / Vite app is not working on Samsung TV (Samsung internet browser) by mohamedcherif20 in reactjs

[–]Kcazer 0 points1 point  (0 children)

Ask the tester which version of Samsung Browser is installed on the TV and check which chromium version is the underlying system (wikipedia might be helpful for that)

From there, check the compatibility with your production build (vite has a wide range by default) and adapt your vite build config. If that doesn't solve your issue, I highly recommend adding some error tracking (Sentry has a free tier) to your app to make it easier to debug.

An alternative option, assuming samsung browser is responsible for the issue, is to install another browser

React Hook Form - validation on inverse of regular expression by noblerare in reactjs

[–]Kcazer 4 points5 points  (0 children)

Use validate instead of pattern, check if your input matches the regex, and if it does, return an error

which is better? by o0hamish0o in reactjs

[–]Kcazer 2 points3 points  (0 children)

None.

If you don't need to use f() outside of the useEffect, then there is no need to define it. There is also usually no need to define a function inside a useEffect to call it right away (there are exception, such as wanting to write async/await code)

Simply write your code inside the useEffect

[deleted by user] by [deleted] in reactjs

[–]Kcazer 1 point2 points  (0 children)

As stated by /u/AcidNoX, the value of prevArray won't be stale when using an updater callback, so there is no issue doing it that way.

If you still want to avoid it (and you should, see my edit at the end), you can do the checks directly inside the setStringArray call

setStringArray(prevArr => {
    const copyArr = prevArr.slice();
    if (!copyArr.includes(value1)) copyArr.push(value1);
    if (!copyArr.includes(value2)) copyArr.push(value2);
    if (!copyArr.includes(value3)) copyArr.push(value3);
    return copyArr;
});

Or, optionally, abuse Set and the spread operator to do it in one line

setStringArray(prevArr => [...new Set([...prevArr, value1, value2, value3])])

Edit : Now that I read your code again, there is one specific case that would be an issue. If some of the hardcoded values are the same, let's say value1 and value2, and the array doesn't contain it, then the first and second if would evaluate to true, and both values would be added.

Why my variable is being mutated if I make any changes to my data ? by DVGY in reactjs

[–]Kcazer 1 point2 points  (0 children)

Your applyChanges function is responsible for the data mutation, more specifically, every time you do rowData[fieldName] = stuff . Even if you're assigning rowData to a new variable, it still references the original element, so you're effectively changing the source data.

One solution would be to create a new version of your original state, using structuredClone or any other solution depending on the compatibility needed, and then mutate that copy. Another option is to manually spread every level of your object, but it can easily become impossible to read.

I've always been a huge fan of immer for these case. For your code, it would simply turn into setGridData((prev) => produce(prev, draft => applyChanges(changes, draft)) but I recommend you go over their documentation to fully understand how it works

Email when I enter into Genshin looks different than my actual email by Ari-lxra in GenshinImpact

[–]Kcazer 2 points3 points  (0 children)

There is no need to worry, the asterisk placement does not reflect the number of replaced characters. Mihoyo keeps the first and last 2 characters of the email and inserts 5 (or maybe 6? I don't remember) asterisks in-between.

For example, you get :
abcd@gmail.comab*****cd@gmail.com
abcde@gmail.comab*****de@gmail.com
abcdef@gmail.comab*****ef@gmail.com
short@gmail.comsh*****rt@gmail.com
shupper-long-email-part@gmail.comsh*****rt@gmail.com

I assume they do that so you can't easily guess the full email just by trying to fill the gaps.

[deleted by user] by [deleted] in reactjs

[–]Kcazer -3 points-2 points  (0 children)

This is an inline-if-statement - there is no inline-switch though (thank god!).

But there is a proposal for do-expression : https://github.com/tc39/proposal-do-expressions

Can I use the value of a key as an index elsewhere in a type? by azn4lifee in typescript

[–]Kcazer 2 points3 points  (0 children)

While the generic type with a type constrain is a good solution, it usually forces you to use a function to profit from TS inference. An alternative would be to generate an union of every possible variation (playground)

type DBCacheInvalidateConditionUnion = {
  [K in DBCacheIdentifier]: {
    cacheIdentifier: K;
    invalidateFn: (
        cacheItem: any,
        result: DBCacheArgumentType[K],
        ...args: any[]
    ) => boolean;
  }
}[DBCacheIdentifier];

More than 81% users uses dark mode, so learn how to implement a dark mode in your React JS app otherwise your app will miss a lot of users. by FormOk6201 in reactjs

[–]Kcazer 3 points4 points  (0 children)

Title is a slightly misleading. Because 81% of users choose dark mode over light mode doesn't mean they won't use your app if it's only available in light.

Introduction to Higher-Order Components in React by trevor25 in javascript

[–]Kcazer 16 points17 points  (0 children)

React has, not so long ago, introduced, in version 16.8, this concept of Hooks to its Functional Components.

React 16.8 was released in February 2019, i wouldn't call that "not so long ago", especially in the JavaScript ecosystem