# Tag Info

## New answers tagged javascript

0

It is fine to write things out as you did, but you want to keep DRY(Dont Repeat Yourself) in mind. That is where defining your own methods/functions comes in when you wan to start cleaning things up. Starting with this: Math.floor(Math.random() * 50) + 3 Math.floor(Math.random() * 90 - 1) + 1 This can be put into its own function to calculate ...

1

Thank you so much for the input! It gave me great insight into solving this problem. Thanks @Jeremy Albright for your insight and advice. It inspired me to rewrite my node.js file. My setup so far: // gatsby-node.js exports.createPages = require("./gatsby/node/createPages") exports.onCreateNode = require("./gatsby/node/onCreateNode") I'm still learning ...

0

Event delegation can be used to improve efficiency. Instead of adding a click handler to every single element with the class download, an event handler could be added to the entire document or a sub-element that contains all elements with class download. document.addEventListener('click', e => { let node = e.target; do { if (node.classList....

0

You should prepare everything (find elements, etc) you can as soon as you can (on document load, assuming the elements Are not added dynamically). Dont wait for user action. Also dont load current location upon checking the checkbox. Load it upon form submit, prevent default submit action And only send to server after location Is obtained. Maybe display ...

3

I know this is a couple weeks old, and you already have a good solution. I just wanted to point out a method that is a bit more deterministic/declarative. You are already using multiple instances of gatsby-source-filesystem, and they each have their own name property. That becomes sourceInstanceName on the File nodes. You can use that value to simplify ...

2

From my experience, this is a good first cut solution for a less experienced candidate as opposed to some experienced candidate. Also, a lot of other info is missing in question such as was there any further discussion on how to improve the solution or about adapting some good practices or how to make this code bug free etc. I will try to list down possible ...

3

Let's start with some convention things, in JS we (everyone) write function and variable names as camel case. I see you have a comment that you tried to use a setter, the issue is that you would then want to use it in two ways. You would want to write this.board = import_string to call the setter, but in the constructor you do this.board = this....

5

To add to existing review a few points I noticed: You are mixing up under_score (clear_webpage_board) and camelCase naming (createArray). Typically functions in javascript use camelCase (you can see that in all built-in methods that you use, including the borrowed createArray). Css on the other hand typically uses naming, where dash is used, so thick-right, ...

2

The code is mostly easy to read- indentation seems consistent, though the CSS rules are not separated by new lines - a common convention among many style guides. There are a few comments and many functions/methods are self-documenting but it would be good to comment each function/method to be thorough, especially if you intend to have others utilize the code....

1

One of the things you should consider is user experience. You are saving the light or dark mode to Session Storage. Everytime the user visits your page he will have to select the mode again and again. If you save it in local storage instead, that will persist even if the user comes back another day. Consider that change. You want the user to do as less work ...

1

After getting detailed feedback from the company, below given is the solution which company expected. This also matched with all the points which nik has explained (the accepted answer above). Create a class with 2 different methods. One to update the average (setAverage here) used by company X and other to get the average (getAverage here) which can be ...

2

Regarding your validations - extract each of your validations in validation object. You can do something like: class Validator { isValid(obj) { //return false if obj is not valid } message(obj) { //return error object if obj is not valid } status() { //error status if validation fails } } Then you can have like EmailValidator, Required, etc. ...

1

I think the nicest thing to do is to split your task into three bits, essentially you want to see if a row, column or diagonal has all the entries the same. A row, column or diagonal can all be thought of just as a (1D) array. In fact, these things are all the 'lines' (pictorially) that you can find in a 2D array (which span the whole array). Now given a ...

1

I didn't analyse your code but this code returns expected values: const firstMissingPositive = (arr) => { const arrSorted = arr.filter( val => val > 0 ).sort( (a,b) => a - b ); const length = arrSorted.length; if (length === 0) return 1; for ( let i=0; i < length; i++ ){ if ( arrSorted[i] + 1 !== arrSorted[i + 1] ) { ...

0

I would think it much cleaner to create a higher order component (factory function) that accepts passed component. You could generate “instances” of your utility object that have the component reference in it’s scope.

3

// ... const getAccountNumbers = user => { return acctData.filter(acc => acc.user === user) .sort((a, b) => balance[a.acctNum] - balance[b.acctNum]) .map(v => v.acctNum) } getAccountNumbers("Alice"); // Returns ["AAA - 9921", "AAA - 8191", "AAA - 1234"]

1

The last component looks quite complicated. I think some refactoring would help with readability but I have no concrete suggestions since I don't really understand what it's doing. Like this here this.state.remove[this.module]. in the comments I wrote some advice in the comments. Hopefully it's understandable. I mention direct state mutations a couple of ...

2

You don't need to use if and <></> for conditional-rendering: getMessages(field) { const { errors } = this.state; return ( errors[field] && errors[field].map((item, index) => ( <Text style={style.inlineDangerMessage} key={index}> {item} </Text> )) ) } You can reuse the ...

2

First, draw and draw2 looks pretty similar to me, you can DRY them class drawingBoard { // ... draw (e) { this.draw2(e) let m = drawingBoardGetMouse(this.cvs, e) curLine = [m.x, m.y] } draw2 (e) { let m = drawingBoardGetMouse(this.cvs, e) this.ctx.beginPath() this.ctx.fillStyle = curColor ...

3

In the matter of simplify Search_User.js instead: var c = cookieArr[i]; while (c.charAt(0) === " ") { c= c.substring(1); } you can use trim() var c = cookieArr[i].trim(); and in IF's use slice or substring with start argument only if (c.indexOf(userName) === 0) { user.userName = c.slice(userName.length) } if (c.indexOf(userId) === 0) { user.userId ...

2

What do you mean optimal? Your thing transforms the object lots of times, which is liable to not be very efficient, if that's what you meant. Here's something that I hope is simple to read that does your task. function sumObjects(obj1, obj2) { return Object.keys(obj2).reduce( (acc, currKey) => ({ ...acc, [currKey]: acc[...

1

For solution (a) - just accept a shorter array at the end code can be very short function mushInLittleArray(arr, size) { let resultArr = []; for (let i = 0; i < (arr.length / size); i++ ) { resultArr.push( arr.slice( i * size, (i+1) * size ) ); } return resultArr; }

0

In large part I agree with K.H. so functions will be a much shorter: function tick() { timeLeft -= 1; if (timeLeft < 0) { // Check if the timer is done clearInterval(timerRun); alert("Timer is done!"); document.getElementById("timer").innerHTML = "Simple Timer"; } else { timeDisplay = Math.round( timeLeft / 60 )...

3

const mergeSortedArrays = (arr1, arr2) => [...arr1, ...arr2].sort((a,b) => a-b); const ar1 =[-7, 2, 4, 22, 66, 99]; const ar2 = [1, 5, 9, 88]; console.log( mergeSortedArrays(ar1, ar2) ); // [ -7, 1, 2, 4, 5, 9, 22, 66, 88, 99 ] I don't know if it's not too simple solution, but one-line Arrow function solves this problem... OR in your code instead ...

4

I think considering approach that you chose, your code is alright. A few points: What I don't like is that you get error when passing 2 empty arrays? Why would you do that? Imagine I am generating arrays of different sizes and using your code to merge and sometimes I would pass 2 empty arrays. Should I really need to handle that as special case in my code? ...

2

Based on your constraints, which are: Single loop variable No restarting of iteration over large arrays You could calculate your looping step sizes first, then go over the array only once. const mushedArr = []; const remainderSize = arr.length % size const numberOfChunks = Math.floor(arr.length / size); let remainderStepSize = Math.floor(...

5

There's definitely a lot of duplicate code in those 2 ifs. I'd extract it into function and pass different things as parameters. Then code would look let's say: //not sure about name of function and parameters function nodeFieldPerType(filePath, getNodePath) { if ( node.internal.type === "Mdx" && node.fileAbsolutePath.includes(filePath) ...

1

You are basically making your object filtering into an $0(m * n)$ complexity function ( where $m$ is number of type id’s) that your are filtering against and $n$ is number of objects in the fetched result set. This function should only be $0(n)$. To do this, make type id’s into a Set which allows $O(1)$ lookup and then use this Set to filter ...

3

You are basically trying to show timer, which can be up to hours. Best way to calculate and represent that for your usecase is definitely by just one variable, which holds all the seconds. That way your code handling current state is a lot simpler - you have just one variable, you decrease it every second until it's done. You will have more work displaying ...

2

I really don't like this svg code in javascript string. Why don't you put in html instead? It's presentation detail of your X and O has no meaning in your code. Edit: or even separate .svg file Extract your data from HTML. Your "data" are in html elements and innerHTML. That's just too tight. Your code is mix of different responsibilities (game itself, UI). ...

2

if (!item.innerHTML) { // Because "" is falsy. If you need to add a comment then maybe the code isn't clear enough. I suggest either comparing it implicitly to an empty string, or using a data attribute to mark it as filled. In checkWin and the onClick listener, instead of relying on the innerHTML value, you should either use a virtual grid state, or save ...

2

This is a good first-cut solution to the functional requirement of stated question. However, when you look at it as production code related to two companies (X and Y) these points arise: Monolithic: The code should be well demarcated across X and Y company logic. A single analytics function is processing all of the logic with an (admittedly, nice) value ...

1

Sᴀᴍ Onᴇᴌᴀ has already pointed out several major issues in your code. Besides those, your code also includes unused variables (e.g. cssFallback) and hard-to-read back and forth control flow (since, for some reason, you've decided to stick the animeFallBack function between the definition of webAnimSupport and the switch statement that uses it and possibly ...

0

Inline style lengths require units. In quirks mode, browsers will assume pixels as the unit, if provided with an integer instead of a length. If you are not sure how the browser will handle the value, specify the units. The CSS parser interprets unitless numbers as px (except for line-height and any other properties where they have distinct meaning, and ...

2

I think this is what you're looking for const uuidGenerator = () => Math.random(); const message = { message: 'hello', recipients: ['John', 'Susie', 'Christian'], }; function split(obj) { const { message, recipients, ...remaining } = obj; return recipients.map((recipient) => { return { id: uuidGenerator(), message, ...remaining, ...

2

Method Names The most method names do not describe what the method really does and what the method name implies. getButtonData let me imply that it returns information about one button getButtonDataByPage the same like getButtonData add implies that something gets added to a collection In generell method names that start with get are known as getter and ...

4

Like I mentioned in my answer to your post Check browser compatibility for RequestAnimationFrame and Vanilla JavaScript .animate() API, many ecmascript-6 features like arrow functions and the let and const keywords are used, which cause errors in some browsers the code aims to target - e.g. IE 10 and older. So instead of an arrow function in the callback to ...

0

Here's a one-liner that also plays nice with dodgy user input (say, injecting ]" into the #selectVal field, which would break Andy E's approach. function setSelect() { $("#mySelect").val($("#selectVal").val()).val($("#mySelect").val());$("#selectVal").select(); } Why this works: the first call to \$("#mySelect").val(...) selects the option if it ...

0

IE version function reloadScript(script) { // Check for existing script element and delete it if it exists var js = document.getElementById(script.id); var parent = script.parentElement; var elementIndex = Array.prototype.slice.call( parent.children ).map(function(e, i) { return e === script && i + "" }).filter(function(e) { ...

0

You can turn the action types to constants. Have action creators https://redux.js.org/recipes/reducing-boilerplate/ In deletePosts you're passing a cb that's never used For readability I would always wrap args in ( ) in arrow function (params) A trivial comment/preference... I would make sure I use data in args so I don't have to assign it to prop axios....

2

I hope this helps. Made some comments in the snippet. /* Create <option> tags */ class OptionTime extends HTMLSelectElement { constructor() { super(); this.setDateRange(); } setDateRange() { const now = new Date(); const year = now.getFullYear(); const unit = this.dataset.range.split(' ')[2]; const startYear = year - 50;...

1

Initial thoughts Looking at the MDN documentation for Element.animate() I see this warning at the top: This is an experimental technology Check the Browser compatibility table carefully before using this in production. Looking at that compatibility table we see it isn't supported at all by a couple browsers... I searched for "navigator.sayswho" ...

1

Yes, this should be more efficient asymptotically function myTwoSum(A, B) { const invertedArrayMap = A.reduce((acc, curr, i) => { acc[curr] = acc.hasOwnProperty(curr) ? Math.min(i, acc[curr]) : i; return acc; }, {}); const secondIndex = A.findIndex( (w, i) => invertedArrayMap.hasOwnProperty(B - w) &&...

4

The answer by Orlyyn explains it well. Just adding to it: You can probably destructure your variables, this helps with readability and reuse. Since you are not using the state of the class you can convert that into Functional Component Use template string instead of doing it in bits. Still no need to add this.state and call setState in your ...

1

File 1: batch_progress.js import React, { Component } from 'react'; import ProgressBar from '../progress_bar/progress_bar'; export default class BatchStatus extends Component { constructor(props) { super(props); this.state = { color: '' } } componentDidUpdate = (prevProps, prevState) => { if (this.props === prevProps) { ...

3

secureRandomIntRange Scheme Basically what you generated with painstaking work is to create an implementation of the Complex Discard Method described in section A.5.2. That's a known secure scheme, so kudos for that. I don't like the way bytes is calculated in the secureRandomIntRange function. It probably uses floating point and that may introduce ...

5

The function render() in only supposed to render. It is not supposed to compute some style, set variables, have any logic other than render: (Functions Names Should Say What They Do). This should respect the SRP (Single Responsiblity Principle), as well as another clean code rule: 'A Function Should Do One Thing'. What could be code smell in your first file:...

2

Variables tempA, index1 and index2 seem to be unused. Since you are only interested in if(j - i > 0){, you can start right there for (int j = i + 1; and omit the conditional. Further the condition if(j < Results[1] || Results.length == 0){ should be flipped around to if(Results.length == 0 || j < Results[1]){ to avoid accessing undefined index. ...

0

This is the Secondary Attempt that I have made & will Add more to it when I have learnt a bit more JS let webAnimationsSupport = (window.Element.prototype.animate !== undefined); let rafSupport = (window.requestAnimationFrame !== undefined); let cssFallback = false; switch(webAnimationsSupport ? 'true' : 'false'){ case "true": ...

5

Not sure that a class definition makes a lot of sense here since you don’t really have any real behavior being defined in this class. Destructuring can also help you populate variables from the input array directly. camelCase is generally preferred in JS vs. snake_case. For example you might simplify to something like this: const conversionFn = ( [ ...

Top 50 recent answers are included