Tag Info

1

setInterval will execute the callback no sooner then 10ms after the call. It doesnt mean it will trigger in 10ms exactly. This makes it possible for the animation to appear not smooth - slower at one time and faster at another time - not that i can see the effect now. Or the overall the animation may get slower then anticipated. But it would be better, ...

1

Yes, it is short. But it is somehow incorrect. Time Complexity Array#splice, Array#unshift will need to move all following element in the list. So it runs under $O(n)$ in your case. Your algorithm runs in $O(n^2)$ then. But a merge sort should be run in $O(n \log n)$. As you know... You can write a even shorter code if you try to use Bubble sort as ...

0

Most code you find online has been written to explain how bottom-up merge sort works. They specifically avoid writing compact code. Writing compact code can be fun, and has a competitive element to it. You might like sites like HackerRank or CodeWars. When writing code which will actually be used in an production environment, length of code is not an ...

0

What I don't like in what I did is : I replace items, so I need to filter from the list of parts the one I want, to keep the one I want to remove it is 4 replaces operations, and I was wondering if it was improvable. It is possible to avoid replacing items. For example, 'use strict'; function getLocaleAddress(parts) { // field and line separators ...

2

With a bit of fiddling I come to this code: function fibonacci() { let s = t = 0, a = 1, b = 2; do { s = a + b; a = b; b = s; t += s & 1 ? 0 : s; } while (s <= 4000000); return t; } console.log(fibonacci()); It is pretty much the same as yours with a few difference: I start with a = 1, b = 2 as per ...

0

One option is to ensure that the sales type is in (or not in) a white list of types using Array.prototype.includes() - for example: filteredSalesAgreementItems() { if (!['bricks', 'mortars'].includes(this.$route.query.salesType)) { return this.salesAgreementItems; } return this.salesAgreementItems.filter(obj => obj.department === this.$route....

2

Computed properties can return objects, which seems useful for you. computed: { filteredItems() { switch (this.$route.query.salesType) { case 'bricks': return { filteredSalesAgreementItems: this.salesAgreementItems.filter(obj => obj.department === 'bricks'), subTitle: 'Bricks', title: 'Bricks' ... 1 I also prefer the second example, due to the functional programming style. I believe it's easier to read because you've decoupled the getter from the transformation. The only change I'm tempted with is to pull out and share the getter logic with some currying. Something like this: const emailGetter = key => o => o[key]; const emails1 = objects1.map(... 0 I am assuming this is a school assignment and an exercise in recursion. A short review; Its okay to have the recursive function be another function, but I imagine you get extra points for 1 single function Destructuring assignment helps with the signature function It's good that your first check in the recursive function is the exit condition Instead of ... 8 Correctness Your code falsely identifies (hi)there as having unbalanced brackets. Formatting The else return false clauses can be replaced with a single return false at the end of the function. There is no need to treat the 0 as a special case. testString() is not a very descriptive name. getReverseBracket() could be unecessary if you restructured the ... 1 Hey Jonathan, welcome to Code Review! There's an easy way to turn those two maps into one. I'm going to tell you how, and give you some general tips as a bonus. Buckle up! ➰ Looping right round (like a record baby) You asked how to prevent yourself from repeating your loops, which is a perfect use case for a Fragment! Consider the following: <row> ... 0 The hardest thing about programming is creating a good project structure, but this is also the most important thing to get correct. Your project is structured well, and cleanly follows the model-view-controller structure, so great job! Your view logic is cleanly separated from the underlying model, and your controller is requesting updates on both the model ... 3 Recursion Recursion in JavaScript is just a toy and should be avoided when ever possible. Why? Untrustable. JavaScript has a very limited call stack and recursive code can quickly consume the call stack. For example getSum(1, 10000) will overflow the call stack and throw an error. Example showing call-stack overflow. sumAll([0, 10000]); function ... 0 Get text before '?' with split('?').at(), then reverse it and get text before '/' and reverse it back ;) supplyUrl.split('?').at().split('').reverse().join('').split('/').at().split('').reverse().join('') 3 Obviously AuthContext from @context/auth is a blackbox to me here, so I'm unable to know if there's a server side auth capability. However, if you're able to retrieve the session server side, then with Next.js, you can use getServerSideProps to redirect to /login if there's no user found. This would prevent the user from seeing any protected content on the ... 3 I think for any url related task you have two good tools as The URL API The URLPattern API With the URL constructor you may do like; var url = new URL("https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars"), tariffCode = url.pathname.slice(url.pathname.lastIndexOf("/")+1); URLPattern API, on the other hand is ... 2 There are many template engines but my question is: Why do they still exist? Can we not achieve the same job with readily available JavaScript Template Literals? Sure, that seems like it would work ok for smaller projects, especially if you remember to keep to the string encoding guidelines to prevent XSS attacks. From my quick glance over your function, I ... 2 Using a Set You are best to use a Set to reduce the complexity that comes with Array.includes. Ignoring the sort. Your code has a complexity of $O(n^2)$ however using a set will reduce that to $O(n)$ Example of $O(n^2)$ dataA.filter(v => dataB.includes(v)); Example of same task with $O(n)$ complexity set = new Set(dataB); dataA.filter(v => set.... 1 If you can, use the URL constructor. It is a bit clearer semantically: const supplyUrl = new URL("https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars"); const parts = supplyUrl.pathname.split("/"); // the 0th item is empty since the pathname starts with a slash const tariff = parts[2]; 4 While it may be unlikely to occur, the URL could contain a hostname with a top-level domain supplier. Currently .supplies is registered to Donuts Inc and someday URLs could have a TLD with supplier, which would lead the current code to not correctly find the target text. const supplyUrl = "https://my.supplier/supplier/tariffSelectionG_E5449168?t=... 5 Super short review; The code should handle the presence or the absence ? in a transparent way The code should probably check for /supplier/ instead of ? That leaves me with function extractTariffName(url){ const resource = '/supplier/'; if(url.contains(resource)){ return url.split('?').shift().split(resource).pop(); } //return undefined } ... 2 A short review; Do you think this is reasonable in daily JavaScript? Probably not, for a few reasons You need a function per record type since this wires metadata and styling so tightly There is a ton of HTML tooling out there, none of it will work with embedded html The html function you provide is compacter but less readable than the one in the blog ... 5 Avoid performing side-effects in the middle of a ternary expression. If you're not using the resulting value of the ternary operation, then you're using it wrong and should be using an ordinary if-then instead. Also, be consistent with your usage of semicolons, and let/const. const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay',... 2 Bugs Your code will throw errors if you include null, or undefined in the data. And your code does not check for cyclic data structures. First some review points. Review Some general review points regarding code style and language feature use. Use RegExp Rather than use String.includes convert the search term to a RegExp with the case insensitive flag. You ... 3 From a short review; The function name is a bit misleading, it does not filter anything really. Could be named hasValue, or even hasString You could also just return the occurrence(s) of where the string is found, this could be more useful typeof returns more than you handle Personally, I would make the toLowerCase() call only if requested by the caller ... 1 I think you are overcomplicating things. You do not need separate logic for objects and arrays. The following should do the job: function filterItem(item, value) { if (typeof item == 'object' || Array.isArray(item)) { for (let i in item) { if (filterItem(i, value) || filterItem(item[i], value)) return true; } ... 2 A longer review; Keep full uppercase names only for constant values like numbers In the ready function you access req.socket.id enough that you could store it locally To me, it is a code smell that you have the socket id in the key and in the value of USERS You mix var with const and let, I would stick with const and let JavaScript variables should be in ... 2 A short review; You inlined the success function, I would use a properly named function outside of that block This$('#favoritepagesListBlock').empty(); $('#meetingsanddisclosuresBlock').empty();$('#memberinstitutionBlock').empty(); $('#orderListBlock').empty(); can be$('#favoritepagesListBlock,#meetingsanddisclosuresBlock,#...

2

First, make your code work. orderShowMore = true is assigning true to orderShowMore - the code in the block after this is inevitably going to get executed. Just go if(orderShowMore). Second, don't use two variables named data - while scoping may make it unambiguous to the compiler, it's confusing to anyone reading your code. Also, consistent indenting goes ...

0

Super short review, as others have said, a function should try to be consistent in the type of data it returns your case statement can be replaced with a clever data structure I prefer <verb><subject> for function names, so convertWordToNumber Personally, after seeing you now return -1 for non found values, I would write this as function ...

1

If the lines are truly perpendicular then you don't need d_ since it is either [dy, -dx] or [-dy, dx]. If I choose the first one and replace d_x by -dy and d_y by dx and substitube this into your function I get: function getIntersection(a, d, b) { const [ax, ay] = a; const [dx, dy] = d; const [bx, by] = b; const µ = (ay*dx + bx*dy - ax*dy - by*dx) / (...

2

Your code is really hard to understand. You'll notice that the other answers found it so hard to understand that they basically ignored what you wrote and instead gave their own attempt. I think I've managed to get through what you intended. You should prefer const if possible (not the case here), let if not const, and var if you have no other option. As ...

3

The first thing that stands out is the casing on variables that are declared like globals. Syntactically there is nothing wrong with it but a common convention in many style guides is to only use all caps for (immutable) constants. This is recommended in many widely accepted style guides, not just for JavaScript (e.g. ESLint, AirBnB, Google) but also for ...

6

Complexity and performance There are many ways to write this type of function and the best is determined by the number of input states. In your example you have 6 different input states 1-5 and NaN. Complexity The least number of steps to parse the string is 1 and the worst requires 6 steps. The average time, assuming equal distribution of input, is (1 + 2 + ...

3

You could use a map or object, but it would be just another way of doing it and I wouldn't call it better tbh. One thing you can change is the default block. All the other cases return a number while default returns a string. Depending on the use case, you can either return a value like -1, NaN, undefined, or even throw an exception throw 'Not a valid value!'...

2

I'm not a Javascript programmer, but it looks strange that we return a different type of result for the default case. Can't we return a number (e.g. 0)? Or a NaN? Or perhaps even throw an exception. I guess that without more context of how the function is used, it's hard to say what the default return should be.

2

You can use the ascii code to understand the position in the alphabet. const findAlphabetIndex = (...chars) => { const base = 'a'.charCodeAt(0); return chars.map((char) => char.toLowerCase().charCodeAt(0) - base); }; console.log( findAlphabetIndex('a', 'A', 'b', 'z'), );

1

The code seems fine except for omitting curly braces and unfortunate naming. I would name the features and their variations. const numbers = [1, 2, 3]; const colors = ["Red", "Green", "Blue"]; const shapes = ["Diamond", "Ellipse", "Swirl"]; const shades = ["Full", "Striped", &...

2

In the ready function, don't add to queue, call queue-handler with id. pop your queue-list and if not undefined you've got a match. else add the user to the queue. Don't know if you need a MATCH-object at all. You're using it as temporary storage between functions instead of just passing parameters. Maybe you need it later? You shouldn't need setInterval ...

1

From a short review asort is not a great name, sortedA could have been better? As mentioned by another user, it is bad practice to change lists you receive as a parameter You only us bi once. I would use b[i] in that one place for readability aj is not a great name, your two letter variables make your code hard to read Once you realize that you can just ...

0

This is how I finally formulated the code such that it sorts the results firstly based on course.name and secondly based on course.description. let foundCourseListName: CourseItem[] = []; let foundCourseListDesc: CourseItem[] = []; const uniqueIds: Set<string> = new Set(); const inputWords = this.state.inputWord ...

7

Like peterSO said in his answer your code appears complicated and it is not so easy to understand without an explanation of the task, moreover the (a[i] + a[i+1] === 0) condition brings with itself not conform outputs to what you expect. An approach to simplify your code is to use the fact that 0 is a falsy value and combine this with a variable storing the ...

5

To make sure I understood the problem, I scribbled a simple solution. // Trim multiple zero's sequences to a single zero digit. // The return value is the updated array. function zeroTrim(a){ let j = 0; for (let i = 0; i < a.length; i++) { if (a[i] !== 0 || (i == 0 || a[i-1] !== 0)) { a[j++] = a[i]; } } a....

Top 50 recent answers are included