how to shuffle a deck of cards using Js - javascript

I searched for how to shuffle a deck of cards that I made and I found these lines but I can't understand...
is (this) that is written in the second line a js keyword or it't just a given name
how does m stores deck.length + i
what does m-- means at the end of the sixth line
what is the function of line no.8
shuffle() {
const { deck } = this;
let m = deck.length, i;
while (m) {
i = Math.floor(Math.random() * m--);
[deck[m], deck[i]] = [deck[i], deck[m]];
}
return this;
}
I know it's a lot to ask but I would appreciate your help

is (this) that is written in the second line a js keyword or it't just a given name
Yes, this is a keyword in JavaScript. I strongly suggest you google "this javascript" to learn how this works. It will take some time to get your head around.
how does m stores deck.length + i
I assume you are asking about let m = deck.length, i;. Notice there is a ,, not a +. m only stores deck.length. i is a separate variable that is declared on this line. I suggest you use the Chrome or Firefox developer tools to step through the code to inspect the value of m. If you are unfamiliar with these tools, you definitely need to learn about them and how to use them effectively, especially to debug your code.
what does m-- means at the end of the sixth line
-- is the post-increment operator. It decreases the value of m by 1 and stores that new value in m. The result after the subtraction is used in the rest of the expression. You can experiment with this operator in your own code or in the JavaScript console.
what is the function of line no.8
[deck[m], deck[i]] = [deck[i], deck[m]]; uses destructuring syntax to swap two values in the array. Again, you can use the debugger in the browser's developer tools to inspect the values of the variables to see what happens.

const and this are keywords
const and let are similar to var, except const cannot be assigned after initialization.
m stores only deck.length. i is another variable, declared by the let
m-- means decrementation, i.e. same as m = m-1 and it gives value of m after that calculation.
On line no.8 You can see destructuring assignment.

Related

How to change the final array to the front in JavaScript?

The case is:
function trocaPrimeiroEUltimo(array) {
array.array[0]
array.array[array.length - 1]
return array
}
I did this way, but it didn't work. I can't change the structure of the function, just what it's inside. Someone, could please help me?
Do you want to replace the last value with the first value?
if so, do:
temp = array[0]
array[0] = array[array.length-1]
array[array.length-1] = temp
That's a simple swap.
The syntax makes use of new ES6 capabilities (destructuring an array). This way the exchange can be done without a temporary variable.
The whole thing can even be done as a one-liner:
const arr=[7,8,9,10,11];
const swapFirstLast=(a,l)=>([a[0],a[l]]=[a[l=a.length-1],a[0]],a);
console.log(swapFirstLast(arr))
The use of the argument l is also something you probably would not do in a "real" application. I only went for it so I would not have to define the variable locally. l is assigned a value on the right hand side of the assignment expression. By the time the result needs to be stored l has been calculated and can also be used for addressing the right target element.

Updating Variables Within Array After the Array Has been Declared (Javascript)

I haven't found this answer anywhere, and have been on the lookout for a few months, so my apologies if I'm overlooking something that should be obvious. Self-taught and came upon a rather vexing gap in my knowledge here.
In an rather complex yarn of connected pieces, I have two globally-scoped (basically static) variables and an array of character types outside of the main onclick function, as such:
var missingWut = ["child","spouse","talisman","relic","sock"];
var rdmmissingWut;
var pronounA = "he";
var charTypes = [
["goatherd",pronounA+" wants to find a missing goat","kind"],
["shepherd",pronounA+" wants to find a missing sheep","cruel"],
["detective",pronounA+" wants to find a missing "+missingWut[rdmmissingWut],"spidery"],
...,
..., //this goes on for awhile; the array is currently 500 items long and has way more subindexes than I wanted/needed to include in this example.
];
We've declared the variable names in the line above, but obviously rdmmissingWut is undefined at this point.
We then - for the sake of memory - go on to define rdmmissingWut inside the function, thereby updating its value from undefined to a random index number:
rdmmissingWut = Math.floor(Math.random()*missingWut.length);
rdmcharType = Math.floor(Math.random()*charTypes.length);
before assigning a random charType index to character 1 (char1).
var char1 = charTypes[rdmcharType];
My question is this -
Is there a way to update the variable value within the array - after I've updated the variable - without redefining the entire array?
One could obviously just reiterate the definition of the array, at which point it would update all variable values with their current value, but that seems really clumsy, cluttered and inefficient.
Another use case (with the same issue):
I want to use this same chartypes array to randomly roll a character type for character 2 (char2) - and eventually, char3 & char4, as well. But let's say char2 (or 3 or 4) is female. To do this, after char1 was defined, I would then need to update the value of pronounA to "she" and thereupon update the pronounA definition in every instance within the charTypes array before selecting a random charTypes index for her - correct? What is the best way to accomplish this? I'm sure there must be some elegant solution that I'm just ignorant of.
Thanks for your help.
You'll be needing to evaluate that variable every time you run through your array, so I'd recommend a placeholder that can be replaced with .replaceAll
var missingWut = ["child", "spouse", "talisman", "relic", "sock"];
var rdmmissingWut;
var pronounA = "he";
var charTypes = [
["goatherd", pronounA + " wants to find a missing goat", "kind"],
["shepherd", pronounA + " wants to find a missing sheep", "cruel"],
["detective", pronounA + " wants to find a missing _missingWut_", "spidery"]
];
function getMissingWut() {
return missingWut[rdmmissingWut || 0]; // this uses zero incase the value hasn't been updated
}
console.log(charTypes.flat().join("\n").replaceAll(/_missingWut_/g, getMissingWut()))
rdmmissingWut = 4
console.log(charTypes.flat().join("\n").replaceAll(/_missingWut_/g, getMissingWut()))

What is this : sign after a variable JS syntax?

I came across the following valid syntax in JS when looking at svelte library:
$: doubled = 6 * 2;
At first, I thought it was specific for the library, but it works on the Chrome console. What is this syntax?
It can be anything:
name: something = 6 * 2;
Any JavaScript statement (kind-of except function declarations) can be preceded by a label:
foo: var x = 0;
What you've got there is something like that:
$: doubled = 6 * 2;
In your statement, "$" is the label.
There's not much point to labelled statements because there's no goto in JavaScript. Both break and continue can include a label of an enclosing loop to indicate how many "layers" should be involved.
wholeLoop:
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == null)
// Oh no! This is terrible
break wholeLoop;
}
}
MDN, spec
All the above is pretty much correct, but apparently Svelte applies its own build-time preprocessor to component source code and translates that into the actual JavaScript sent to the browser. This use of the label syntax is "hijacked" by them to mean something; see Quentin's answer.
This is label in JavaScript.
The interesting point here is how Svelte is using this to bind variables to other variables. Here's a portion of a video where Rich Harris explains this.
Essentially, in Svelte, $: means re-run whenever these values change
If we look a the example in Svelte's Reactive declarations example,
<script>
let count = 1;
// the `$:` means 're-run whenever these values change'
$: doubled = count * 2;
$: quadrupled = doubled * 2;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Count: {count}
</button>
<p>{count} * 2 = {doubled}</p>
<p>{doubled} * 2 = {quadrupled}</p>
The variables doubled and quadrupled have $ label. So, they'll be computed again when count or doubled changes respectively.
If you take a look at the compiled code, you can see
let doubled, quadrupled;
$$self.$$.update = ($$dirty = { count: 1, doubled: 1 }) => {
if ($$dirty.count) { $$invalidate('doubled', doubled = count * 2); }
if ($$dirty.doubled) { $$invalidate('quadrupled', quadrupled = doubled * 2); }
};
So, each time the update happens, there is a dirty check for those variables and update.
In conclusion. $: in Svelte doesn't have anything to do with JavaScript label. It's a directive for Svelte compiler to have the code for updating those variables. $: is of course valid syntax but outside the context of Svelte, it doesn't do what it does in Svelte. It's the compilation that does the magic ;)
In JavaScript, it is a label and is designed to be used when using break and continue in conjunction with nested loops (so you can pick which loop you are breaking or continuing from).
Svelte appears to use some kind of hack to give it alternative meaning. See the tutorial:
Svelte automatically updates the DOM when your component's state
changes. Often, some parts of a component's state need to be computed
from other parts (such as a fullname derived from a firstname and a
lastname), and recomputed whenever they change.
For these, we have reactive declarations. They look like this:
let count = 0;
$: doubled = count * 2;
To add more detail to the answers already provided:
It essentially defines a 'destiny operator' in Svelte (a destiny operator is a general concept of 'reactive programming')
A destiny operator ensures a variable is updated whenever values that it's computed from are changed)
Rich Harris (the creator of Svelte) wrote an article a while back about use of the destiny operator, that explains the concept well (although at the time he didn't specifically suggest using $:
https://gist.github.com/Rich-Harris/aa3dc83d3d8a4e572d9be11aedc8c238
For Svelte.js specifically, that $: Marks A Statement as 'reactive' meaning that it will update based on the variables that follow - as others have also written that's a label in javascript, but in svelte it has special meaning.

JavaScript function "help text" in console

I'm curious to know how one could easily annotate a JavaScript function with textual information (description of what function does, which parameters are used, returned etc..), so that one can access it from the console.
In Matlab for example this is done by commenting text right beneath the function's header, and accessing it by typing help myFunction in the console.
Example from Mathworks:
myFunction c = addme(a,b)
% ADDME Add two values together.
% C = ADDME(A) adds A to itself.
% C = ADDME(A,B) adds A and B together.
%
% See also SUM, PLUS.
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end
What is the (or an) equivalent approach in JavaScript?
Javascript isn't really geared for interactive use, so there's no standard pattern for this in the language.
Functions are objects, though. So you could assign a value to myFunction.help:
function myFunction(a, b) {
…
}
myFunction.help = "Here is some help text";
This value wouldn't be specifically exposed anywhere in the console, but would be available by reading myFunction.help.
You can add documentation (params, return, behavior etc) to a JS function using JSDoc. But it is not available in an interactive way like you need. It includes a document generator which can generate user-friendly (static) HTML pages out of the documentation, which you can browse.

Javascript: TypeError variable is undefined

I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the template.php they call this function:
function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
for(i=0; i<checkedAnswers.length; i++){
alert(checkedAnswers[i]);
}
}
Function checkExerciseRB is my generic function, it is called from checkAnswers.
function checkExerciseRB(rbuttons, opciones, correct){
var answers = new Array();
var control = 0;
for(i=0; i<rbuttons.length; i++){
var noPick="true";
for(j=0; j<opciones; j++){
if(rbuttons[control+j].checked){
if(rbuttons[control+j].value==correct[i]){
answers[i]= 1;
noPick="false";
break;
}
else{
answers[i]=2;
noPick="false";
break;
}
}
}
if(noPick=="true")
answers[i]=0;
control=control+opciones;
}
return answers;
}
It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:
TypeError: rbuttons[control + j] is undefined
Any clue on how to deal with this matter?
This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].
You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.
You’ll watch it, and you’ll think “Oh! That line of code is wrong!”
You're looping through rbuttons.length times, but in each loop you're adding 2 to control. Using control to index your array, you're going to run past the end.
Does the index specified by control + j exist in the array? i.e: If that evaluates to 4, is there at least 5 items in the array?
Also, you should be using var i, var j, etc inside your for loop. Without it your variables are leaking into the scope this code is executed in (most likely the global scope, and that's not good) :)

Categories

Resources