New answers tagged

0

Constants The first thing to look at is the use of strings to represent the signs. The problem is, that if you mistype a string somewhere (for example, "rook" instead "rock") you'll have a bug, that you'll may be difficult to find. Instead define constants, that you use in place of the string literals: const ROCK = "rock"; const ...


1

In no particular order; If your constructor takes an object and then applies the key/pairs of that object you might as well go for Object.assign(target, source); like this; constructor(template) { Object.assign(this, template); } I feel like you release a spot, not a vehicle. I would rename releaseVehicle to simply release. Furthermore it is super ...


1

Code Quality Remove the fluff As I understand it, the Spot class exists purely to help implement the ParkingLotManager class. It exposes a couple of public functions that never get used by ParkingLotManager() and can be removed or made private. The constructor to Spot() current allows you to set a starting vehicle, but no code is using that feature either, ...


2

Functions Always write code as functions. Even when its just an example, writing code as a function gives it a name, and make you think in terms of that name. Functions should be as simple as possible doing one thing only. (see rewrite) Review USE SEMICOLONS!!! Don't add code that is redundant or superfluous. Eg var secondPlace = null can be var ...


3

Your Question Is this really the right way of doing this, or is there a better way? Something doesn't feel right here. The term "better" is subjective so you can judge for yourself. Presuming there is not a need to have clicks on the child elements trigger any event handlers, one alternative is to use the CSS property pointer-events style. One ...


1

const getFavouriteShows = (graphql, favShows) => ({ ...graphql.filter(gql => favShows.map(show => show.slug).includes(gql.slug)) )} Breaking it down: favShows.map(show => show.slug) returns an array of the slug value for each show graphql.filter(gql => [...].includes(gql.slug)) returns an array of elements where gql.slug is in the [...] ...


0

You can also use string templating. Something like this: const points = { '204255221017214977': 3, '208993609255485441': 5, '382197942762602496': 4, '664606841409634324': 5, '779857709155090432': 4, '381084508276916225': 5, '794200859612545075': 4, '155149108183695360': 4, '438978127973318656': 3, '...


1

Your code would benefit from separating data and display. Results can also be constructed by using the .join() method on an array, reducing the need for checking boundaries. I'm not sure that these modifications resulted in "easier" code, but the singular point of truth makes it harder for bugs to hide. const points = { '204255221017214977': 3, ...


0

Responses to your questions I think for this specific case, a two-dimensional array would is a great data structure to solve the problem of multiple ticket queues. Like you mentioned, giving concrete names to each ticket queue would just add complexity to the code, because you would then have to sort the named queue by priority whenever you want to use them ...


0

I eventually made things a little bit more Object-oriented and the code now looks like this: if(as_knight){ if(square.isKnight){ rtn.isAttacked = true; } }else if(square.isKing){ if(!i){ rtn.isAttacked = true; } }else if(square.isQueen){ rtn.isAttacked=true; }else if(piece_direction%2){ if(square.isRook){ rtn....


1

Similar but different functions can be merged by using parameters. function toggleItem(itemId, buttonId) { var item = document.getElementById(itemId); var displaySetting = item.style.display; var button = document.getElementById(buttonId); if (displaySetting == 'block') { item.style.display = 'none'; button.innerHTML = 'Show ...


1

A short review This code passes jshint perfectly, well done. Besides the obvious warning that you did not provide swap of course The name arrayCopy is perhaps unfortunate, since this works on any array whether it is a copy or not The name bubbleSort also does not perfectly describe what is going on, it not only bubble sorts the array, but it also tracks the ...


3

A short review; You can avoid process typeless and admin users by using an upfront .filter() obj is a terrible name (it implies the parameter is just an Object instead of an Array, list would be better, something meaningful like userDetails the best If you want to go for slightly less efficient code, you could replace the whole loop with 2 filters Dont go ...


-1

The goal here is that we want to make the placement/release of cars as efficient as possible, ideally O(1). ... Is there any situation you think I might need to use a spot Id The cart is before the horse, requirements wise. I don't see how any parking lot can operate without clearly labeled slots, or at least "section" markers with row numbers....


2

Array.some In the loop when flagResumeAll becomes true nothing more will change thus it is best to exit the loop. If flagResumeAll is already true then nothing can be done inside the loop so you should not even start it. The same with type if not 0 or 1 then the loop will do nothing. Using the first example as a guide to what your code should do you can use ...


2

It looks like the main difference between your original code snippet and the two revisions is that you're using .filter() instead of .forEach() - both of which came out around the same time, and both of which came out a while ago (IE 9 supports both). It looks like you aren't doing any significant changes to the code that would improve speed, so you will ...


1

You could avoid the unwrap logic by emulating a callable object. This is done by creating a function and attaching members to it. Your predicate class will then boil down to this small chunk of code: const predicate = fn => ( Object.assign((...args) => fn(...args), { and: otherFn => predicate(value => fn(value) && otherFn(value)), ...


2

UI I noticed that when I add a new task I tried to click on the text "New task" to replace that with the text of the task but then I didn't get a cursor, so then I clicked on the text labeled "Task" and started typing - I could barely tell my text was added but it was black so it was difficult to see it against the black background. ...


1

HTML: Your input elements do not have associated labels Use semantic html elements. Why do You use img instead of a regular html button ? CSS: Avoid styling by tags. Use classes instead Avoid using !important. Read about CSS specificity I'd personally create a separate CSS file with the colors I'm pretty sure You do not need all of those prefixes JS: ...


0

HTML The formating could be a bit cleaner (</head> on its own line, superfluous spaces around =, content of <div id="menuBar"> not indented). on... attributes shouldn't be used. Event handlers should be assigned in the script. I don't believe &#9776; ("Trigram For Heaven") is a suitable character to use for a menu icon. ...


3

Since ES6 there is a cleaner solution with Object.fromEntries: const url = 'https://tempuri.org/?token=secret&test=true'; const params = new URL(url).searchParams; Object.fromEntries(params); It will output an object like this: { token: 'secret', test: 'true' } See browser compatibility of Object.fromEntries on MDN. Basically all browsers and Node.js ...


0

I agree that JSON.stringify isn't the most appropriate for this problem, not just because it's slower, but also because it's a bit harder to understand. And you're also right in assuming that reduce() isn't the best tool for the job. Using a .map() reads in a much more natural way. const convert = obj => ( Object.entries(obj) .map(([key, value]) ...


2

Helper Functions I see that you've already asked a separate question for the helper functions here, and others have already done a fine job answering it, so I won't add anything to it here. The rewrite I came up with will use a variation of the helper functions that operate directly on the byte array as defined below - this isn't necessary, but I felt these ...


6

Keep it simple OMDG it took me longer to work out what your code was doing than to write a solution. Some of it seams to have taken the most complex possible path to a solution, and I am still not 100% sure (as I gave up deciphering that code) what the buf_get_with_leading_space means with leading_space. I am assuming you mean leading off bits? I get the ...


0

I believe your code is O(n^2*m), where n is the target and m is the source. Overall, though, I think there are a lot of readability improvements that could be made here by separating functions and renaming variables (j is a particularly bad contender). // indexCharacters('hello') // = {'h':[0],'e':[1],'l':[2,3],'o':[4]} const indexCharacters = source => { ...


1

I believe you could retain the same level of flexibility without managing extra objects by using higher order functions. This also has the advantage of treating the predicates as functions and nothing more. const records = [ { name: 'Andrew' , age: 21, position: 'Developer' }, { name: 'Bill' , age: 26, position: 'Developer' }, { name: 'Chris' , ...


4

If I were doing this, I'd start by putting the data into a 2 dimensional array. As raw data, it seems to be pretty much this: default 12 24 36 48 60 36 -0.2 -0.1 0.0 0.15 0.3 48 -0.1 0.0 0.1 0.25 0.4 60 0.0 0.1 0.2 0.35 0.5 I don't do a lot of JavaScript, but I think in JavaScript syntax, that works out to something on this general order: var priceTable ...


2

There is some very bad naming in the code. Names are too long and have overlapping abstractions. What is a category, there are two types a, b, or c and testnum1 and itemNum2 Due to poor naming the function has lost so much semantic accuracy it takes a second look to see what it is doing. What are you doing? getCategorizedItems getting categorized items?? ...


1

I decided to take a crack at simplifying this problem myself as it sounded like a fun challenge. @SᴀᴍOnᴇᴌᴀ already offered a bunch of good advice. The main thing I want to add is how important it is to be able to split up the logic into well-named and easily understandable helper functions. You did have one small helper function in there, but one or two more ...


2

I would start by extracting the relevant data from itemList and create a lookup object that maps the category to the relevant key/itemCategory. const itemCategories = new Map( Object.entries(itemList) .map(([itemCategory, {category}]) => [category, itemCategory]) ); With the above structure you can filter the items and only keep the items that have ...


4

Short review; Unless you are writing inline functions, you should stick to using function Using semicolons is preferred, it takes skill and knowledge to avoid the pitfalls of not using semicolons You assign in 1 statement the value of categorizedItems and return it in the next, you might as well return immediately In essence you do a find within a map, not ...


6

I would Encapsulate the names and colors in a data structure Use .map instead of .forEach So something like this; function chartBackgroundColor(collection){ const nameColorMap = { "TripAdvisor": "#00B98B", "Google": "#FFBD00", "Facebook": "#4B6DAA", }; return collection.map(data =...


0

Only what is needed Programming is a creative process and things like time pressure have a negative effect on the whole project (even little 90min projects). That said software development is a business that must be profitable. Time is a limited resource so there will always be time pressure. As a coder you must write efficiently, spending time on details ...


1

The answers here are great, especially if you're looking to implement this algorithm in a faster way (which would be very important to do if there could potentially be a lot of points - the current implementation would be slow on large lists). ...however, I didn't see anything in the problem description about speed being a needed factor. I tend to put code ...


0

deck.js The Card class can be removed entirely by writing newDeck() like so. newDeck() { this.cards = []; for (let i=0;i<this.packs;++i) { for (const suit of suits) { for (const value of values) { this.cards.push({value,suit}); } } } return this.cards; } Shuffling logic can be separated from ...


1

I've managed to join the links and the todo list in my modular 'compiler server'. I've added some more features too and I've had some growing pains with the code. Components have a minimum size for good interactions. Changing the todo component to the width of the links module makes the todo component horrible to use. Whilst I've dropped the width from ...


1

I realize this question is old now, but it's intriguing and still getting a number of views, so I though I would give it a shot. Now days there's a very easy solution to this: Just use async/await syntax instead so that you can use normal flow-control statements to get the job done. However, I'll write this under the assumption that this task needs to be ...


1

closePath is not complement of beginPath You are using ctx.closePath() incorrectly. ctx.closePath() is a path function, similar to ctx.moveTo(x, y). It creates a line from the current position to previous ctx.moveTo(x, y). It is not the complement of ctx.beginPath(). There is no need to use it in this case. Keep it Simple. Circle & Vector You have ...


2

I'll start out by doing some a general code-quality, just with your app.js. Then I'll go over some of the other questions you had. app.js code quality suggestions Let's start with this chunk: var words = []; fs.readFile('dico.txt', 'utf8', (err, data) => { words = data.split('\n'); }); While often asynchronous versions of a function is preferred, ...


2

I like this question. Validator stuff You probably meant &gt; instead of &gt You should consider adding a charset meta tag like <meta charset="UTF-8"> You should wire newInput(); return false in JavaScript, HTML is not a good home for JS You are missing a number of semi colons in room.js Not strictly validator issues, but using a ...


3

Can you send the timestamp instead? Manipulating dates in JS is a bit tedious without a library. This is probably pretty clear to you already from having to declare all the y M d h m s variables. PHP, on the other hand, has createFromFormat, which has a flexible and friendly API. For example, I believe you could pass a formatting string of 'Y m d H i s' (...


1

Bugs There are 3 bugs, or two depending on input. Both functions use an undefined variable. entries which should be either listAsString or change the argument listAsString to entries The second function does not return the correct values. This function is not at all worth considering because you are iterating the set for each item in the set. Sets use ...


1

This isn't quite debouncing. It's similar, but it's not the same thing, at least not in the way debounce is commonly understood in the programming community. With debouncing, when an event is triggered, the function to run later may be delayed (if the event was triggered recently), but it's never skipped entirely. See here for an animated example of what ...


1

Looks mostly fine, though there are a few issues: Argument bug/typo You're referring to top-level variable entries inside the function instead of to the listAsString argument. Match numbers? Even if it's said that the input will contain line-separated numbers, I'd feel safer matching numeric characters instead of splitting by newlines. It'll be more robust ...


0

I think the solution with the timeout variable is far more clear, and avoids arithmetic operations. However, your implementation has some odd behaviours. That is, using debounce with a high frequency will postpone the callback indefinitely. const debounce = (func, interval) => { let timeout = null; return ()=>{ if (timeout) return ...


2

Intent Reading only the code The code gives hints at some higher level use, but what that could be is unclear. I will use intent to fill the blanks Good code provides more than just an understanding of the logic, but conveys intent. The strongest guide to intent is naming, I find this more true for less experienced coders. Deducing intent From the naming map,...


2

TL;DR This code snippet is rather taken out of context and is likely symptomatic of bigger issues in the codebase as a whole. You may have bigger problems than trying to improve these few lines of object initialization. A few minor points... For starters: 'use strict'; Good start! let map = {}; Use const. Using let says "I'm going to re-assign this ...


3

Fundamentally, not really. When you need to create a nested structure, there are no built-in ways to get around explicitly testing if the intermediate object(s) exist, and creating them if they don't. (If you just wanted to access a possibly-existing nested element, you could use optional chaining to achieve it concisely, but nested creation is much more ...


4

Use classes instead of creating a function that manually inheirts from React.Component. This will also allow you to more concisely define properties and methods. For example: class App extends React.Component { state = { minefield: dummyMinefield(mines.difficulties.get(descriptions[1])), }; get difficulty() { return checkedRadio('...


1

Bug The second function does not work. The break will exit the inner loop before all arrays have been processed. Having a short arrays does not mean the following arrays will also be short. However looks like you copied it from an answer so not really your code (apart from the bug you added). Question "What do you think about my code?" The first ...


Top 50 recent answers are included