New answers tagged

2

Short answer: You can include setExpanded in the dependency array. Long answer: The function passed to useEffect will fire only when at least one of the dependencies changes: useEffect(() => { // runs // - on mount // - on every render }) useEffect(() => { // runs // - on mount only }, []) useEffect(() => { // runs // - on mount ...


0

Looks like you were trying to follow the best practices on not mutating data but this is an overkill: when processing data locally in a function there's no need to clone the intermediate data no need to clone the array in return, it's already a temporary cloned array reduce is the wrong choice here - at least if you keep its needless duplication of the ...


0

Regarding the self "trick", don't use it, just switch to arrow functions which preserve this: this.fullName = ko.computed(() => this.first_name() + ' ' + this.last_name(), this); Regarding the main concern, simply call those functions via .then and pass the data via return in the previous .then handler: Passing of data: this.getQuote = quoteNumber ...


1

You have the right idea, and your function almost works, but your code is only checking that ( is balanced with ), and [ is balanced with ]. So it will handle cases like aaa(bbb[ccc]ddd)eee correctly. But it will also accept aaa(bbb[ccc)ddd]eee, and that is wrong. You should only have a single stack, and you should push all the opening brackets onto it. ...


2

Just some quick/general thoughts here, not really an in-depth analysis. Regarding performance, it's imperative to use devtools performance profiler (or its simpler version "JavaScript profiler" in Chrome) and optionally other more specialized tools for node.js, etc. Otherwise you'll get a rehashing of the well-known practices which most likely have little ...


2

I wouldn't say the code is difficult to follow but I do have some suggestions. The first thing I notice is that some variables are declared with let. Many of those variables never get re-assigned. It is wise to use const for any value that shouldn't get re-assigned - even if it isn't a constant. This helps avoid accidental re-assignment. The values in ...


2

A few things stood out to me: You can extract out the implementation details behind where the token exists. Not a huge deal, but personally I would do this: const setAuthToken = (token) => document.querySelector('meta[name=csrf-token]').setAttribute('content', token) const getAuthToken = () =>document.querySelector('meta[name=csrf-token]')....


2

It seems this could be simplified with a small lookup table and then concatenating strings. Using a table as simple as: const lookup = { blue: 'b', green: 'f', purple: 'g', yellow: 'p' }; we can then lookup the color values and concatenate them together. Combined with a simple check to make sure the color is valid and the 2 colors aren't the same, ...


0

@RoToRa: thanks for your suggestions, I edited my code: called it classAction (wanted something short but hey - anyone could name it to gusto) made the suggested simplifications couldn't replace the classIndex() function with indexOf() though since Array.prototype.indexOf() is only supported by IE9+ (thus it would defeat the whole purpose of using this) MDN ...


2

Usually if I have a big list of mappings from one string to another, that is likely to be later enhanced on, I use a generic mapping method, that is fed a static mapping constant. So the first iteration would be something like: type ExpectedMimeTypes = 'image/png' | 'image/jpg' | 'image/jpeg' | 'application/pdf' | never; type ExpectedMagicOutput ...


0

The only numbers one should use in coding are 0, 1, and many. This code implicitly uses 2, the number of special cases, "[]" and "()", for which you wrote code. So right away you know the fundamental design is wrong. If this were a real program and next week your boss told you to handle "<>" as well, you'd have to write another section of code. Then ...


5

A short review; checkBalancedBrackets("([)]") returns true, not sure that was the intention b1 and b2 are not great names, what does the b stand for? Using arrays is not needed, all the code does is counting numbers, you can just use numbers The inconsistent use of curly braces in your if and else if clauses is not good


3

stop using recompose because it got deprecated and you don't need it if you use react hooks. transform your components and use react hooks because it's an anti-pattern to use them with class components. Try to decompose your components more like for the shell components it's a heavy component try to extract for say the drawer component to its own file Drawer....


3

First : I recommend you to change this line in your code in order to anybody can use it easily without changing or editing it. set SaveDest=C:\Users\ME\Desktop\Wallpaper\%dte%.jpg by those lines : set WallpaperFolder=%userprofile%\Desktop\Wallpaper If not exist "%WallpaperFolder%" MD "%WallpaperFolder%" set SaveDest=%WallpaperFolder%\%dte%.jpg Second : ...


1

Per se returning a promise from an Angular Service is not bad, however there are numerous things in Angular world that are heavily based on Observables: usually you will likely change the change detection to ChangeDetectionStrategy.OnPush in your components and this will most likely be easier with Angular's async pipe not a problem, because async also ...


2

I'm not a big fan of neither the function name classes nor the parameter name type. Something like modifyClassOfElement and action would be better fitting. You should define constants for the type/action values. It's convention in JavaScript to have a space between keywords and a following open bracket: if ( In classIndex the second if is unnecessary. ...


3

It has been a while since I worked with jQuery so I may not get specific API's correct. You are repeating ("slide", { direction: "left"}, 250), if you ever changed one of the properties I would assume you'd want them to be consistent with each other. You can set an array then destructure that when calling show or hide. You can also apply this theory to your ...


3

You could check the sign of the item and the predecessor and if unequal take a new array as group. function createSubArr(array) { let result = [], group; for (let i = 0; i < array.length; i++) { if (Math.sign(array[i - 1]) !== Math.sign(array[i])) result.push(group = []); group.push(array[i]); } return result; } ...


3

const returnNegatives = arr => arr.filter(n => n < 0) const returnPositives = arr => arr.filter(n => n >= 0) const mixedArray = [1, 2, -4, 2, 5, -6, -3, 3, -6, 8, 9, 0] console.log('The negatives', returnNegatives(mixedArray)) console.log('The positives', returnPositives(mixedArray)) Edit: Think I misunderstood what you wanted with ...


0

Additionally to the other comments, i would think about the following: Magic values vs. constants The percentage for the tips (30%, 20%, 10%, 5%) are "magic numbers" that are used in the text and in the calculation. In bigger programs, when you have to change such a value (30% to 31%) you can nearly bet, that one of the occurances is missed. The ...


1

There are a few suggestions I could make, but the one that really stands out is that your serviceQuality function is misnamed. It doesn't return a service quality, it returns a calculated tip amount.


2

A couple of things to consider: When dealing with a switch statement, if a case utilizes the return keyword then you do not need to also include a break. When the return is hit, no further code in that function will be reached. You should handle unexpected inputs; for example, serviceQuality should account for non-numeric inputs, or a number that is not 1-5....


2

the code has plenty of room for improvement, and yes it violates the solid principals like the Single responsibility principle "your functions are way too big and the module in itself has too many responsibilities ", to clarify there are no rules on how API should be written in NodeJS there are code practices and design patterns that help us developers ...


1

Based on your code, you can reuse the console.log and delete by putting them in a function. I don't have all the data in order to run the code, but this is one approach of refactor. for (let i = 0; i < 100; i++) { deleteIfNull(file_1h[i]); deleteIfNull(file_20h[i]); deleteIfNull(file_20d[i]); deleteIfNull(file_40y[i]); } function ...


1

Basically we search for the most close number from array where our number belongs. After we find the min value, we take the index of it and add 1, because the rank starts from 1 //rank 1 : 150 - 500 //rank 2 : 500 - 1000 //rank 3 : 1000 - 2000 //rank 4 : 2000 - 3500 //rank 5 : 3500 - 5000 //rank 6 : 5000 - 5500 let pointsRank = [150, 500, 1000, 2000, ...


-1

Here is the solution using ES6 array.map() with no for-loop used, which to me is the most clear and intuitive solution: function staircase(n) { // intiate an empty n*n matrix let matrix = Array(n).fill().map(() => Array(n).fill()); matrix.map((curArr, idY) => { // for each array row in matrix curArr.map((curVal, idX) => { // ...


2

Your code does not work - process.hrtime() does not return with a timestamp of any useful form unless you compare it to another process.hrtime() in the same running program (typically used for measuring performance). From the documentation: These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not ...


3

there is no right in wrong in this situation it's a question of what's best for your particular situation if you are going to build many Rest API endpoints it's best to separate them in separate files under routes like this so your code can be more maintainable : │ ├── routes/ | | |___index.js |___auth.js |___gizmo.js ...


0

The shortest one:) +new Date()


1

The function declarations are at least lacking a const statement (or let or var if you prefer): const getSpanishCardinal = cardinal => { However I would suggest to using regular function statements instead. The getCardinals function is a bit pointless. A simple constant instead would make more sense: const CARDINALS = { 0: "cero", 1: "uno", // ....


0

This seems reasonable. The most important part is that you do not mutate the react state in-place. By doing let currentUser = [...users]; you copy the state and instead mutate the copy, then assign it as the updated state. An alternative would be to use .map and .filter to make your changes. I see this pattern more often than the state copy approach. ...


1

function computerPlay() { let choices = ['rock', 'paper', 'scissors']; return choices[Math.floor(Math.random() * choices.length)]; } In the above function, you create the choices array again and again. This is a waste of time and memory. It's better to create the choices once and for all: const choices = ['rock', 'paper', 'scissors']; function ...


2

All in all, a basic review of your question shows that you are creating objects numerous times, when they do not need to be. Other things are pointed out in comments. const choices = ['rock', 'paper', 'scissors'], capitalize = word => word.charAt(0).toUpperCase() + word.slice(1), // Should these be made into 1 function, that takes another ...


2

Use if.else if.else if ladder: Instead of multiple conditions of if.if.if, you should use if.else if.else if ladder. The advantage of latter is that once a condition is met, the next conditions are skipped. But using only if.if.if means all the ifs are walked through irrespective of any if matching the condition. Read more about it here It is generally a ...


4

Use meaningful variable names (and element IDs), for example, startDateInput instead of input/myInput. Declare varables in the smallest needed scope instead all of them at the start of the function, and declare each variable in a separate statement. Use let or const instead of var (unless you need to support enviroments that don't support them). Move the ...


0

I don't know what complexity it is but still let it be as a variant function findSubstring(subs, string) { let z = 0; // current index of given subset let x = 0; // current index of subset we check right now let q = 0; // indicator that allows us to increase x let s = 0; // indicator that helps write position of string after first subset symbol is ...


0

I prefer use functional and prototypical inheritance over native loops because it's cleaner. And I use MAP because ES6 feature is far more short and useful, though MAP has no side effects. const reversedArr = (n) => Array.from(Array(n).keys()).reverse() const staircase = (n) => reversedArr(n).map((value, index) => { return console.log('...


1

Some comments: Use the built-in database promise support in mysql2 rather than promisify stuff yourself. In Model, don't hide low level database errors. If the database has an error, let the caller see the error. It's up to the caller what to do with errors. There's no reason for your Model.getStats() to be async. Service should use promises to ...


1

Because this question is tagged with object-oriented, I will focus on some improvements based on the oop-design. Currently your code uses objects, but this does not mean that it is object-oriented. When we take a look to your code all methods are global. With objects we can couple the methods to an object. For example: The methods addBookToLibrary and ...


0

I did a recursive solution using powers of two times the divisor. Essentially, it finds the highest divisor * 2^n that still fits in the dividend, subtracts it and repeats. const divide = (dividend, divisor) => { if (dividend === -2147483648 && divisor === -1) return 2147483647; const result = dividePositive(Math.abs(dividend), Math.abs(...


3

I agree, that your naming is mostly alright, no point to document these variables. Except for event variables. What I seriously don't like about your approach is how tightly it is bound to html. For example removeBook takes as parameter event, which you use to extract element and use that one to extract data that you use to remove. That is bad from many ...


2

You're using redux for state management. The problem with mixing local state and redux state is that component render cycles are asynchronous, which oftentimes can cause finicky race conditions. If you're going to use redux, commit to it. If you aren't using any middlewares like redux-thunk, I highly suggest you do so. Dispatching actions and making api ...


3

Your implementation is basically a Map or Object that revolves around a very specific rule. That rule being the id directly correlates to the index in the array. The advantage an Array has over other data structures, with superior search speeds, is the fact that they are ordered. If order doesn't matter and you're purely using it to leverage search, Sets and ...


2

Data entry I am not much of a React fan so this is not a how to React, rather, fonts are best handled as sets of pixels in the simplest form possible. Fonts are subject to change and it should be as easy as possible to make changes. There is nothing worse than having a complicated long winded data entry process to define visual content. The easier it is to ...


2

Josiah's answer covers most stuff pretty well. The only additional suggestion I have is an alternative to a switch statement: a lookup table of actions. Something like: const query_types = { 1: (x)=>{ frequencyArray[arr[1]] = (frequencyArray[arr[1]] || 0) + 1; }, 2: (y)=>{ ... }, 3: (z)=>{ ... } }; for(let i=0 ;...


4

There's a few general code hygiene things that I'll look at first, and then I'll comment on the algorithm design. First, const should mean constant. I know that in Javascript you don't get in trouble for changing the contents of a const array but it's still confusing to use it with a variable whose job is to change. const arr I like but const resultArray I ...


2

Bug JavaScript strings are Unicode. Your code assumes that the characters in the string are less than 256. If a character is over 256 the resulting binary encoded string will be the wrong length and the hash will fail. Typed arrays and DataView There is no need to convert the numbers to a string of zeros and ones. The conversion is a massive CPU overhead, ...


4

Consistency Sometimes the word color or colour is used to describe the look of a Square. Because I'm not a native English speaker I looked it up on wikipedia: color (American English), or colour (Commonwealth English) The Algorithm Currently Digit calculates the form of a concrete digit based on the prop with the name digit. The calculation is inside a ...


2

You can use ternary operator(?:) or logical AND(&&) operator and React Fragment to avoid this big if-else. The if-else with repetitive code violates DRY principle and should be avoided as any update to the code will be required at 2 different places which will be prone to error in case one is missed const SearchScreen = ({ navigation }) => { ......


Top 50 recent answers are included