Below is one of conditional statements from the source code of d3.min.
What is this checking for?:
value >= value
Here is the entire source code:
export default function min(values, valueof) {
let min;
if (valueof === undefined) {
for (const value of values) {
if (value != null
&& (min > value || (min === undefined && value >= value))) {
min = value;
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null
&& (min > value || (min === undefined && value >= value))) {
min = value;
}
}
}
return min;
}
It could be a peculiar form of checking against NaN (EDIT: and undefined):
const foo = 0/0; // NaN
let bar;
console.log(foo >= foo);
console.log(bar >= bar);
Although why would anyone write it like that, instead of using the isNaN method, I cannot tell. It's shorter than, say !isNaN(value) && value !== undefined, but I'm not sure the tradeoff in legibility is worth it.
Here's the >= comparison table created with editing this JSFiddle.
You can see value >= value is true except when value = undefined or value = NaN:
Related
I was only allowed to use google document for writing.
Could you please tell me what I did wrong? The recruiter wont get back to me when I asked her why I failed
Task 1:
Implement function verify(text) which verifies whether parentheses within text are
correctly nested. You need to consider three kinds: (), [], <> and only these kinds.
My Answer:
const verify = (text) => {
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
}
};
return parenthesesStack.length ? 0 : 1;
}
Task 2:
Simplify the implementation below as much as you can.
Even better if you can also improve performance as part of the simplification!
FYI: This code is over 35 lines and over 300 tokens, but it can be written in
5 lines and in less than 60 tokens.
Function on the next page.
// ‘a’ and ‘b’ are single character strings
function func2(s, a, b) {
var match_empty=/^$/ ;
if (s.match(match_empty)) {
return -1;
}
var i=s.length-1;
var aIndex=-1;
var bIndex=-1;
while ((aIndex==-1) && (bIndex==-1) && (i>=0)) {
if (s.substring(i, i+1) == a)
aIndex=i;
if (s.substring(i, i+1) == b)
bIndex=i;
i--;
}
if (aIndex != -1) {
if (bIndex == -1)
return aIndex;
return Math.max(aIndex, bIndex);
} else {
if (bIndex != -1)
return bIndex;
return -1;
}
};
My Answer:
const funcSimplified = (s,a,b) => {
if(s.match(/^$/)) {
return -1;
} else {
return Math.max(s.indexOf(a),s.indexOf(b))
}
}
For starters, I'd be clear about exactly what the recruiter asked. Bold and bullet point it and be explicit.
Secondly, I would have failed you from your first 'for' statement.
See my notes:
// Bonus - add jsdoc description, example, expected variables for added intention.
const verify = (text) => {
// verify what? be specific.
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
// this could have been a map method or reduce method depending on what you were getting out of it. Rarely is a for loop like this used now unless you need to break out of it for performance reasons.
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
// parenthesesStack.length - 1 === -1.
// parenthesesStack[-1] = undefined
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
// “ will break. Use "
// would have been more performant and maintainable to create a variable like this:
// const textOutput = text[i]
// if (textOutput === "(" || textOutput === "[" || textOutput === "<") {
parenthesisStack.push(textOutput)
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
// There is nothing in parenthesisStack to pop
}
};
return parenthesesStack.length ? 0 : 1;
// Will always be 0.
}
Not exactly what the intention of your function or logic is doing, but It would fail based on what I can see.
Test it in a browser or use typescript playground. You can write javascript in there too.
Hard to tell without the recruiter feedback. But i can tell that you missundertood the second function.
func2("mystrs", 's', 'm') // returns 5
funcSimplified("mystrs", 's', 'm') // returns 3
You are returning Math.max(s.indexOf(a),s.indexOf(b)) instead of Math.max(s.lastIndexOf(a), s.lastIndexOf(b))
The original code start at i=len(str) - 1 and decrease up to 0. They are reading the string backward.
A possible implementation could have been
const lastOccurenceOf = (s,a,b) => {
// Check for falsyness (undefined, null, or empty string)
if (!s) return -1;
// ensure -1 value if search term is empty
const lastIndexOfA = a ? s.lastIndexOf(a) : -1
const lastIndexOfB = b ? s.lastIndexOf(b) : -1
return Math.max(lastIndexOfA, lastIndexOfB)
}
or a more concise example, which is arguably worse (because less readable)
const lastOccurenceOf = (s,a,b) => {
const safeStr = s || '';
return Math.max(safeStr.lastIndexOf(a || undefined), safeStr.lastIndexOf(b || undefined))
}
I'm using a || undefined to force a to be undefined if it is an empty string, because:
"canal".lastIndexOf("") = 5
"canal".lastIndexOf(undefined) = -1
original function would have returned -1 if case of an empty a or b
Also, have you ask if you were allowed to use ES6+ syntax ? You've been given a vanilla JS and you implemented the equivalent using ES6+. Some recruiters have vicious POV.
I have checked the other Q/As. Mine is a bit different and I'm new to ReactJS.
Following code for setting const variable evaluates 0 as false/undefined
and value returned from myFunc is "" :
function formatAmount(x){
if(x === undefined || x === null) return "";
return(x.toLocaleString("en-US",{style: "currency", currency: "USD"}));
}
//When user.bill.amount == 0 this line evaluates it to false!!
const amount = user?.bill?.amount || user?.statement?.amount;
function myFunc(){
return(formatAmount(amount));
}
I tried expanding it with a function and IF conditions but the value returned by myFunc is "$NaN":
const amount = () => {
if(user?.bill?.amount || user?.bill?.amount === 0){
return user?.bill?.amount;
}
if(user?.statement?.amount || user?.statement?.amount === 0){
return user?.statement?.amount;
}
}
Expected:
When user.bill.amount == 0, myFunc should return "$0.00"
Actual:
myFunc returns empty string when user.bill.amount == 0
I think the problem here is 0 is falsy so when using || operator 0 will evaluate to false.
const amount = user?.bill?.amount || user?.statement?.amount;
If your environment supports the nullish operator that would work here.
const amount = user?.bill?.amount ?? user?.statement?.amount;
there's something that i just solved but I don't understand why i got that kind of behavior, here's my js code
function fibonacci () {
let fibonacciNumber = document.getElementById("my-input").value;
let numberInitialize = 0;
let numberNext = 1;
let sum = numberInitialize + numberNext;
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
for (index = 1; index < fibonacciNumber; index++)
{
numberInitialize = numberNext;
numberNext = sum;
sum = numberInitialize + numberNext;
console.log(sum);
console.log("premier tour");
}
console.log(sum);
document.getElementById("fibo-result").innerHTML = `${sum}`;
}
So on the html side I just have an input and im writing down number, my questions concerned this line of code
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
when im writing down 0, its still printing one but i write the condition like that
if (fibonacciNumber === "" || fibonacciNumber <= 0) {
return (0);
}
its working and when I got 0 as an input nothing is printed like i wanted, my question is: Why when im putting fibonacciNumber === 0 return (0) its not working properly its 0, the condition match no ?
Thanks guys
The reason is because your field actually has the string "0". The identity operator (===) will not do any type coercion before comparing the values, so "0" === 0 is false.
Numeric comparison operators like <= will do type coercion, so "0" <= 0 will evaluate to true.
You can see this all in action below.
console.log("0" === 0);
console.log("0" <= 0);
You will need to use parseInt() and then treat the input as integer.
let fibonacciNumber = parseInt(document.getElementById("my-input").value);
I wrote this if block but am not fully satisfied with it. Is there a way to further reduce the lines and still be readable leveraging ES6 or ES7?
export default function validation(str, props) {
const {
length, minLength, maxLength, required,
} = props;
if ((required && str.length === 0) || // check string length only if required is defined
(length && str.length !== length) || // check if string length matches only if length is defined
(minLength && str.length < minLength) || // check if less than minLength only if minLength is defined
(maxLength && str.length > maxLength)) { // check if greater than maxLength only if maxlength is defined
return false;
}
return true;
}
Since if expression is supposed to be boolean, and the function returns boolean value according to it, if can be omitted.
Code can be made self-documenting by introducing intermediate variables:
function validation(str, props) {
const {
length, minLength, maxLength, required,
} = props;
const isEmpty = (required && str.length === 0);
const isDifferentLength = (length && str.length !== length);
...
return !(isEmpty || isDifferentLength || ...);
}
You can shorten the function by destructuring props. You can also return the boolean result directly.
export default function validation(str, { length, minLength, maxLength, required }) {
return !((required && str.length === 0) ||
(length && str.length !== length) ||
(minLength && str.length < minLength) ||
(maxLength && str.length > maxLength))
}
If you use an arrow function, you can also remove the return.
const validation = (str, { length, minLength, maxLength, required }) =>
!((required && str.length === 0) ||
(length && str.length !== length) ||
(minLength && str.length < minLength) ||
(maxLength && str.length > maxLength))
The most succinct way I've found is by using object destructuring default values:
function validate(str, props) {
const { length = str.length, minLength = length, maxLength = length, required } = props;
return (!required || !!str.length) && str.length >= minLength && str.length <= maxLength;
}
I have created a function that return the min and max value, if the user selects" between" or just the min or max based on the operator the user selects.
When the user selects the "between" operator and enters the MIN value, it displays and error msg even when the min value is positive and is a number.. I want it to only display the error message on;y after the max value is enter and only if the max value is incorrect.
How can I display the error message Only when both min and max are entered.. incorrectly.
function minmaxval(min, max, op) {
var rVal = "",
msg = "",
errormsg = "Enter a Max Value larger then Min Value and all number should be greater then 0!",
errormsg2 = "Enter a number greater then 0!";
if (operator === "between") {
if (this.getNumber(min) !== false && this.getNumber(max) !== false && (min < max) && (min > 0)) {
displayMessage(min, max, msg);
rVal = "(" + min + " - <span class='truncate'> " + max + "</span>)";
} else {
if((min!="")&&(max!="") &&(min>max)) {
displayMessage(min, max, errormsg);
rVal = "";
}
}
}
return rVal ;
}
displayMessage(min,max,msg) {
document.getElementByID("#err").innerHTML=msg;
)
Within your operator === "between" block, find this:
if (this.getNumber(min) !== false && this.getNumber(max) !== false && (min < max) && (min > 0)) {
...and change it to this:
if ( (this.getNumber(min) && min > 0)
|| (this.getNumber(min) && this.getNumber(max) && min < max)
) {
In your posted code you're requiring both getNumber(min) and getNumber(max) to be true in order for your first condition to execute, instead of displaying an error message. Change that so your first condition will execute if EITHER getNumber(min) is true and min is greater than 0 OR both are true and min is less than max. Be sure to include the parenthesis so the operators are evaluated in the proper order.