Hot answers tagged

7

Some general remarks: The method name removeAll is misleading, as it does not remove all elements from the array. I would call it for example removeMatching. The method parameter is a closure, but acts as a predicate, so predicate might be a better name. The counter variable in the method is actually the array index so you could call it index. The method ...


7

As I already noted in your other question, trying to validate email addresses correctly is an almost impossible task; there are a lot more characters allowed that you are assuming. Check out this correct regex to validate addresses, which is quite unpractical. This means that we can either be too strict or too lenient with our regex. For front-end ...


6

Your function controls average rate not rate. Your function can let more function run than you want in the interval given. Say you have 3 calls over 5 seconds. The first call starts the timer, then at 4.9seconds just before the time interval expires, you call the function twice. Then just after the time interval expires (@5.1 seconds)you call the function ...


5

I would recommend reading this article by Eric Lippert You'll definitally want an extension method for this... let me hit the google real quick.... Using some inspired code from this SO post I wrote this. static class Extensions { private const HashSet<Type> NumericTypes = new HashSet<Type> {typeof(decimal), typeof(byte), typeof(...


5

Slight issue in your JavaScript. I can't find s declared. I assume it should have been settings. String concatenation inside a loop is not a good idea for performance. I'd also try to keep the addition to the DOM till after the loop. you can treat some values as truthy/falsey instead of === if you know you have set them. if(s.answerCorrect === false) is ...


5

From a code review perspective, I'd say: The function, "passthrough", is doing two things and doesn't describe what it does very clearly. I'd suggest two functions here, "filterAttributes" and "structToQueryString" (or whatever their exact purpose is) The long filter logic could be concisely expressed as a regular expression to avoid the long line of logic (...


4

First of all, you are correct. One way to prevent deep nesting is to pull out the callback into it's own named function. This allows you to only be as deep as 2-3 levels in blocks of code. function task1(){ async1(task2); } function task2(){ async1(task3); } function task3(){ async1(task4); } Another way to do it is by using flow-control libraries ...


4

OK, now that I've had coffee, here's my refactoring: function extractCodeCentricAttributesToMarkupSafeAttributes(attributes){ var relevantAttributePattern = "^(?:data-|ng-|on)(?=\S)"; return attributes.filter(function(attribute){ return attribute.reFindNoCase(relevantAttributePattern); }).reduce(function(attributeString, attributeName, ...


4

Compared to a solution using the upper/lowerCased() string methods, your approach has some disadvantages: It does not work for many letters in non-english alphabets: print(solve("ćœßπĆŒΠ")) // çij¿ΠæIJ΀ It transforms non-letters as well, to some unexpected output: print(solve("a b,c")) // A@BLC Even if the code is only needed for ASCII letters ("A" ... "...


3

Your code isn't quite right, as far as I can tell. In the snippet below, you can compare it to Underscore's version. function throttle(func, interval){ var toExecute = true, queue = false; var result; return function doThrottle(){ var args = Array.prototype.slice.call(arguments); if(toExecute){ toExecute = false;...


3

This isn't the way to compare two dates...it violates one of my commandments. We can & should use NSCalendar's compareDate method: extension NSDate { func isSameDayAs(date: NSDate) -> Bool { let calendar = NSCalendar.currentCalendar() let dif = calendar.compareDate(self, toDate: date, toUnitGranularity: .DayCalendarUnit) ...


3

Groovy is weakly typed, so you could save a some cruft using def for local variables. Typing can give nice hints (great on an API), but it can also be ignored, leading to code lies and confusion. Final is also a pretty pointless keyword in Groovy. There's also a shortcut to collecting properties: the spread operator *, which allows you to do removalFiles*....


3

Consider for a moment, if you will, how we typically handle a user tapping a button. We typically will do so with an @IBAction method. What are the Apple suggested defaults when we hook up a button this way? The default is to give us a method that takes an object of type AnyObject as its only parameter. We can, of course, change the type to specify ...


3

You could do this: casper.on 'step.complete', do -> # invoked right away i = 0 -> @echo "Step#{ ++i }" # implicitly returned function Parentheses: None :-) The do keyword is the equivalent of (-> ...)(), i.e. it means "invoke the following function immediately" (it's also useful to avoid closure pitfalls in loops, by the way.) The ++i will ...


3

IMO, inlined functions add clutter. I think it's clearer and cleaner to use a named function. function makeBlockFunc(i) { return function(){ var blockLen=Math.min(32768,len-(i*32768)); stream.push(i==(blocks-1)?0x01:0x00); Array.prototype.push.apply(stream, blockLen.bytes16sw() ); Array.prototype.push.apply(stream, (~...


3

This seems like a desperate attempt to find a use for closures, and I believe your problem would be solved much more simply by making $rec an object, perhaps even a tied object that lets you overload indexing Some observations: It makes the API much less useful when the calling code has to know which form of data it is dealing with anyway. ret_col_sub ...


3

The first is a pretty straightforward for loop with modular arithmetic, skipping 0: The problem in this code is that you are mixing output with the algorithm logic. The second (and, as a disclaimer, I will almost certainly not be using this in actual production code, I wrote it more for my own learning), is based on closures: I vouch for your decision. ...


3

The first problem I see is that your rate-limit logic is on the client side. You should never rely entirely on client-side code, they're easily bypassed. Nothing stops me from endlessly curling to that endpoint directly or code that calls the AJAX directly. Instead, implement that rate-limiting logic on the server-side. When the user reaches some threshold, ...


3

I like what you've done! I don't have too many comments about the content of it, since it looks good. However, you'll see below that I changed the field name value to cache and some of the generic parameter names, just to make things a little clearer. This is just a subjective preference, but I used F for function, K for key, and V for value. Another thing ...


3

I'm not certain how you even got this to work. The decoration of the class occurs when the class is declared, not when an instance of the class is created, so setting of log_file will not have happened by the Engine constructor. You must have also declared the log_file elsewhere, and that is what is being used to decorate the class methods. If I ...


3

This is a partial answer, that only addresses style, but I prefer something like this for the changeColor function. I'm not thrilled with activateColorButton, but it works. This is much more readable and maintainable to me: const changeColor = e => { const lightOrange = "rgb(221, 238, 255)" const lightBlue = "rgb(255, 238, 221)" const {...


2

As Shmiddty said, you want your Battle object to be more of a namespace providing access to the modules: var Battle = function () {} Battle.Character = (function (/* dependencies */) { // constructor var Character = function (name) { this.name = name; }; // instance method Character.prototype.useItem = function () { [...] }; // ...


2

When talking about OOP, there are several concepts which are common to OOP languages, like encapsulation, dynamic dispatch, polymorphism, and abstraction. Of all these, I can only see that you are trying to implement encapsulation (in the sense of information hiding), although you could still do it slightly simpler in my honest opinion. Generally, if your ...


2

as a personal preference I like the "Right" way that you have listed. it looks cleaner to me. On the other hand I see lots of Java and JavaScript where they have nested functions that are not used anywhere else in the code, personally I don't like this, it looks way to complicated and if you want to use the inside function later on you have to rewrite it ...


2

Your application does not regard Separation of Concerns. Which makes it unmaintainable and untestable. For example: You store your application state in DOM. If you are not experienced enough to know that it's just bad, consider this: string js-quiz-body-question found 6 times throughout the code. Every piece of code should be as DRY as possible. Look for ...


2

You are going very well. There is nothing wrong with it, except there are some things that can be further improved. To improve it you can further do: addCompany should be in pascal case i.e. AddCompany Try to use this i.e. use this.something instead of using addCompany.something everytime. Module name should be noun instead of word. You may use Company ...


2

You could obviously try parcels.max{it.count}. max and other useful operations on Groovy Collections are explained in the following article: https://groovy.codeplex.com/wikipage?title=Collections


2

If you are creating a database wrapper, why not make a lib out of the wrapper and stick it into a lib directory that other modules/classes can import? So, your Users class would be in a directory structure like this: project/ account.py lib/ database.py user.py zombie.py Your database.py would look something like: import pymysql ...


2

Okay, your question is very ambiguous, but I'll give it a shot. First, is seems like you're confused about what a closure is. A closure is simply accessing a variable that was not defined inside that function. For instance, in: function foo () { var bar = 9; function bla () { return bar; } } bar can be accessed because of closure. Read ...


2

Yes this is correct, I believe class for classes was renamed to static. The only thing that I would change is the line static let secondFormatter = { (Void) -> NSDateFormatter in to static let secondFormatter : NSDateFormatter = { which is more readable, because you can immediately see that it's an NSDateFormatter.


Only top voted, non community-wiki answers of a minimum length are eligible