What is the purpose of =+ in JavaScript [duplicate] - javascript

What does the +d in
function addMonths(d, n, keepTime) {
if (+d) {
mean?

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.
Reference here. And, as pointed out in comments, here.

Operator + is a unary operator which converts the value to a number. Below is a table with corresponding results of using this operator for different values.
+----------------------------+-----------+
| Value | + (Value) |
+----------------------------+-----------+
| 1 | 1 |
| '-1' | -1 |
| '3.14' | 3.14 |
| '3' | 3 |
| '0xAA' | 170 |
| true | 1 |
| false | 0 |
| null | 0 |
| 'Infinity' | Infinity |
| 'infinity' | NaN |
| '10a' | NaN |
| undefined | NaN |
| ['Apple'] | NaN |
| function(val){ return val }| NaN |
+----------------------------+-----------+
Operator + returns a value for objects which have implemented method valueOf.
let something = {
valueOf: function () {
return 25;
}
};
console.log(+something);

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.
Example (using the addMonths function in the question):
addMonths(34,1,true);
addMonths("34",1,true);
then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

Related

refers to a value, but is being used as a type here. Did you mean 'typeof ' ? ts(2749)

I was developing a minesweeper game in typescript. But while defining a type named Cell, I encountered an error.
Code:
Not Working
const bomb = "💣";
const flag = "🚩";
export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | bomb | flag;
export type Board = Array<Array<Cell>>;
While defining type Cell the error raises:
'bomb' refers to a value, but is being used as a type here. Did you mean 'typeof bomb'?ts(2749)
while doing it in another way without any variable or constant works:
Fine
export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | "💣" | "🚩";
What am I doing wrong? What is the reason?
bomb and flag and not types.
The typeof operator will give you access to the type of a value.
const bomb = "💣";
const flag = "🚩";
export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | typeof bomb | typeof flag;

How to get substring dynamically

How can I get substring dynamically, I want to split one word into two parts one is a string and other to no,
AA112 this is my string so from sql query
SELECT substr(thisColumn, 1,2) AS String from thisTable
I am getting AA in the query the index(2) I am pasing is dynamic I am getting from some value, So here I am able to get the string now I want to get the number +1 like it is 112 then -> 113
I have tried several queries but it is not working, I have tried doing it with javascript substring but it didn't work out.
Sample output
AAA123 -> AAA and 124
AA4 -> AA and 5
BBBB8 -> BBBB and 9
const input="AA112";
var numberPattern = /\d+/g;
const number = input.match(numberPattern)[0];
const text = input.replace(number,"");
console.log(text); //AA
console.log(number); //112
const incremented = parseInt(number) + 1;
console.log(incremented);
Using LOCATE, IF,LEAST and SUBSTRING over two sub-query can achieve the output result you're looking for.
SELECT VAL,
SUBSTRING(VAL,1,FIRSTNUM-1),
SUBSTRING(VAL,FIRSTNUM,999)+1
FROM
(SELECT VAL,LEAST(V0+0,V1+0,V2+0,V3+0,V4+0,V5+0,V6+0,V7+0,V8+0,V9+0) FIRSTNUM FROM
(SELECT VAL,
IF(LOCATE(0,VAL)=0,999,LOCATE(0,VAL)) V0,
IF(LOCATE(1,VAL)=0,999,LOCATE(1,VAL)) V1,
IF(LOCATE(2,VAL)=0,999,LOCATE(2,VAL)) V2,
IF(LOCATE(3,VAL)=0,999,LOCATE(3,VAL)) V3,
IF(LOCATE(4,VAL)=0,999,LOCATE(4,VAL)) V4,
IF(LOCATE(5,VAL)=0,999,LOCATE(5,VAL)) V5,
IF(LOCATE(6,VAL)=0,999,LOCATE(6,VAL)) V6,
IF(LOCATE(7,VAL)=0,999,LOCATE(7,VAL)) V7,
IF(LOCATE(8,VAL)=0,999,LOCATE(8,VAL)) V8,
IF(LOCATE(9,VAL)=0,999,LOCATE(9,VAL)) V9 FROM mytable) A ) B;
Here I use LOCATE to find the location of the number occurrence in the value then REPLACE to change the value to 999 if it returns 0. This is essential for the next operation using LEAST because if I leave it 0, it'll return all 0 instead. The reason I use LEAST is because if you look at the 4th data example in the fiddle it's AAAAA321. This will return the result in grid like the following:
+----------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| VAL | V0 | V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 |
+----------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| AAA123 | 999 | 4 | 5 | 6 | 999 | 999 | 999 | 999 | 999 | 999 |
| AA4 | 999 | 999 | 999 | 999 | 3 | 999 | 999 | 999 | 999 | 999 |
| BBBB8 | 999 | 999 | 999 | 999 | 999 | 999 | 999 | 999 | 5 | 999 |
| AAAAA321 | 999 | 8 | 7 | 6 | 999 | 999 | 999 | 999 | 999 | 999 | <---this
| AAA45 | 999 | 999 | 999 | 999 | 4 | 5 | 999 | 999 | 999 | 999 |
+----------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
The first number occurrence is actually '3' but because I construct the query running from 0-9, I'll always get the first number in front (in this case '1' is the 8th occurrence) despite it being on the middle or last position. That's why LEAST will correctly take which number is actually located first using LOCATE function.
In the last outer query, I use the result from the LEAST function (assigned as FIRSTNUM) as the defining value for the SUBSTRING. The first substring I use it as the end location subtract by 1 to get the strings and in the second substring I use it as the first location to get the number (I end the location with 999).
Fiddle: https://www.db-fiddle.com/f/F15cxiYJxGcozYUbQukeB/5
Edit: I realized I cannot use REPLACE because if the location is like 10, it will replace 0 to 999 which makes it become 1999 instead. So I use IF.

What does the expression `p[i&1]+=v,p` mean?

I was practicing my javascript with CodeFights and after I finished an exercise I saw this function as a result:
// Subject :
// Several people are standing in a row and need to be divided into two teams.
// The first person goes into team 1, the second goes into team 2,
// the third goes into team 1 again, the fourth into team 2, and so on.
// You are given an array of positive integers - the weights of the people.
// Return an array of two integers, where the first element is the total weight of
// team 1, and the second element is the total weight of team 2
// after the division is complete.
// Example :
// For a = [50, 60, 60, 45, 70], the output should be
// alternatingSums(a) = [180, 105].
// answer
alternatingSums = a => a.reduce((p,v,i) => (p[i&1]+=v,p), [0,0])
I don't understand what p[i&1]+=v,p means.
The & symbol is a bitwise binary operator.
To understand what would happen, you have to convert each item to binary.
| i (decimal) | i (binary) | i & 1 |
|-------------|------------|-------|
| 0 | 0 | 0 |
| 1 | 1 | 1 |
| 2 | 10 | 0 |
| 3 | 11 | 1 |
| 4 | 100 | 0 |
| 5 | 101 | 1 |
Effectively, every even number will be transformed to 0, and every odd number will be transformed to 1.
If I was trying to achieve that outcome, I personally would have used the modulus operator (%)
p[i%2] += v;
But that's just me.
The other part is that there are two statements separated by a comma:
(p[i&1]+=v,p)
That's saying "Perform this action, then return p. It's shorthand for:
alternatingSums = a => a.reduce((p,v,i) => {
p[i&1]+=v;
return p;
},
[0,0])
It looks for an element of the p array that has index of i&1 - it is a bitwise AND operation. Then, increments its value by a value of v variable. Finally, returns the value of p variable.

Angular ngModel doesn't update when `ngModelChange` keeps value

I have a text field represented as: field = {text: "", valid: false}, and an input with [(ngModel)]="field.text".
I want to make that field only accept a defined set of characters (for this issue, numbers), and doing (keypress) doesn't work on mobile, so I did: (ngModelChange)="fieldChanged(field)"
The method does the following:
fieldChanged(field) {
console.log(field.text);
field.text = Array.from(field.text).filter((char:string) => "0123456789".indexOf(char) != -1).join("");
console.log(field.text);
}
And it's behaviour is extremely weird.
Legend:
- input: what key was pressed
- before update: first console.log
- after update: second console.log
- output: what I see on screen in the input
| input | before update | after update | output |
|---------|---------------|--------------|--------|
| "" | "" | "" | "" | <- starting position, no event
| "a" | "a" | "" | "a" |
| "a" | "aa" | "" | "aa" |
| "4" | "aa4" | "4" | "4" |
| "a" | "4a" | "4" | "4a" |
| "a" | "4aa" | "4" | "4aa" |
| "4" | "4aa4" | "44" | "44" |
Why does it always update the output when I enter a legal character? It should be working for each event call.
Edit:
Plunker
I think the cause is that modifying the value on ngModelChange breaks change detection, for example if you change the value back to the previous value, because an invalid character was added.
A workaround:
constructor(private cdRef:ChangeDetectorRef) {}
fieldChanged(field) {
console.log(field.text);
field.text = Array.from(field.text).filter((char:string) => "0123456789".indexOf(char) != -1).join("");
console.log(field.text);
var tmp = field.text;
field.text = null; // or some other value that normally won't ever be in `field.text`
this.cdRef.detectChanges();
field.text = tmp;
this.cdRef.detectChanges(); // I guess this 2nd call won't be necessary
}
If anyone having the issues in updating the value, use setTimeout function while updating
// setTimeout function
setTimeout(() => {
field.text = temp;
this.cdRef.detectChanges();
}, 1);

Valid false values

Converting any value to Boolean returns false or true. For example:
> Boolean (false)
false
> Boolean (null)
false
> Boolean (undefined)
false
> Boolean ("")
false
But 0 is special, because it's a number. I consider is as a valid false value:
> Boolean (0)
false
Are there any other valid false values?
As per ECMA 5.1 Standards, Truthiness of an expression will be decided, as per the following table
+---------------+-------------------------------------------------------+
| Argument Type | Result |
+---------------+-------------------------------------------------------+
| Undefined | false |
+---------------+-------------------------------------------------------+
| Null | false |
+---------------+-------------------------------------------------------+
| Boolean | The result equals the input argument (no conversion). |
+---------------+-------------------------------------------------------+
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
+---------------+-------------------------------------------------------+
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
+---------------+-------------------------------------------------------+
| Object | true |
+---------------+-------------------------------------------------------+
So, you have missed -0 and NaN.
console.log(Boolean(-0));
# false
console.log(Boolean(NaN));
# false

Categories

Resources