_.js / Underscore — as you scroll through all the small utility functions, you'll discover that most of them are just clever compositions of other functions. For instance, see <code>_.defer</code> or <code>_.reduceRight</code>
ES5 does not have classes. Its has objects and prototypal inheritance. Don't try to use those as if they were classes. Its just not the same thing.
Its possible to use some libraries to give you some behavior that might feel a little bit more like Java classes. For example underscore.js has a helper function called extend that you might find useful. Its still not exactly a Class, in the traditional OO sense, but the implementation of extend here will give you something closer to the style of inheritance you're used to.
> With the latest version of php,
Does this not also hold true for the latest Javascript, or more specifically latest ECMAScript?
If your starting from ground zero and you want to choose between php or js. I would highly recommend Javascript, above php. Because you can do both backend and frontend dev. I also feel JS has better tooling, you can start to play with Javascript in your browser right now.
But as you mentioned rather focus on design principles and understanding basic programming concepts like if, for, etc. If he is going the js route I would also recommend him looking into functional JavaScript; Read through the underscore annotated source code, etc.
As for recommending a js web stack I would go with expressjs.
disclaimer: I work daily in php 5.3. While php is a de facto hacking language, it is ugly. They are trying fix it with PHP 7. But every-time I type array(
I die a little bit inside, and it is something they only fixed in 2012(with 5.4)... took a while to realize array/list is a big programming principle. Also if your starting out to program I would recommend python above js and php.
Good luck!
Handlebars or, even more lightweight, Mustache. Also, you can try _.template in Underscore.js if you are planning to use it (or already using it) in your project. And for more "vanilla" solution, you can write your project in ES6, where templating is built-in.
Here's my understanding: json
is the result of parsing--it's an Either
. The _Right
focuses on the correct case, which is a JSON document. Then we access properties of the JSON document: like json.data.children
in JavaScript. Since children
is presumably a list, values
lets us apply a lens to every element. This is essentially like pluck from _.js, except more general. Then, for every value, we access value.data.title
as a string. The final _String
handles the possibility that there is a different JSON type in title
.
In pseudocode, we can think of the whole thing as parse(json).data.children.map(o -> o.data.title)
. Except with better error-handling.
I hope that helped :P.
Don't worry about name collisions. As a potential user I would be fine using the namespace to disambiguate. In general, using namespace std;
is discouraged, from what I have seen. For instance, here and here.
That being said, if you really wanted to use a different naming convention, you could borrow from the convention used by some other languages (e.g. map
instead of transform
, filter
instead of copy_if
). I could suggest the container operation names used by Underscore, as an example.
Several things imo:
1) Read the source for popular open source projects. You can learn a ton by reading code like that and seeing new techniques. Then you usually have to google it because you have no idea why they did that. Here's a good start: http://underscorejs.org/docs/underscore.html The bonus with underscore is that it's annotated very well
This video is also great https://www.youtube.com/watch?v=i_qE1iAmjFg
2) Build lots of varied little projects. Games especially are really great because you run into interesting algorithmic or UI problems.
You could start with a game of tic tac toe. Then move on to snake. Then sudoku. Then a simple pac man clone. The graphics can be really bad, and that's ok because that's not the important part.
Beyond that I would ask yourself if you care more about learning JS specifically, or you want to learn domains? For me, I like learning various domains like how can I write a very simple:
I favor short projects that are 1-2 steps beyond my reach. If I'm too ambitious it's overwhelming. Good luck!
There are a few widely-used libraries that include a whole plethora of such utility functions:
Read the source of underscore.js or backbone.js.
They might not be as wildly popular as they once were, but the source code is expertly annotated and easy to understand for a moderately-experienced JS developer.
Underscore and Backbone have fantastic annotated sources. jQuery's source is also surprisingly readable, but pretty massive.
Are you using underscore in your project? There's a built in invert function that does this.
You can also just do it manually pretty easily.
var newObj = {}; Object.keys(original).forEach( (key) => { newObj[original[key]] = key; })
Just watch out for repeated values in your original object, as only one entry will survive in the inverted object.
Biggest thing that should ALWAYS be done with $(window).scroll()
: throttling.
If you notice, as you scroll down the page, you lose 60 FPS because you’re trying to fire a very expensive operation thousands of times per second. Throttling limits this greatly, so that your .scroll()
event listener only fires as much as you tell it to (ideally, 60FPS, or roughly every 17ms
). While it isn’t that noticeable on your site in particular, it will really start to choke the entire page on more graphically-heavy sites.
Example: https://gist.github.com/karlwestin/3163157
I wish I had learned this sooner, and I still see this on more sites than I should. It’s the difference between “sputtering” animations and silky-smooth transitions.
Second thing (minor): try not to write to the DOM if possible (like when you write top:
, background-color:
, etc. to your <header>
element, instead you could simply add/remove a class to handle the transition (for example, you could add/remove a is-sticking
state class to handle positioning, background, etc.). That way you keep your CSS in your CSS, and you’ll get a smoother animation because CSS transitions are smooth; DOM writing is prone to sputtering. You can use jQuery to calculate a scroll threshold, and when that’s reached simply add or remove the class as necessary.
Fun fact! if a library/framework (say, underscore/lodash or jQuery) you'd want to use for convenience isn't included on the site you'd like to scrape, you can do the following to include it:
var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'http://underscorejs.org/underscore.js'; document.head.appendChild(script);
Going from personal experience, I learned Vanilla JS with the aim of improving my understanding of the syntax and it's uses in solving problems.
Things like taking the underscore library and trying to write the function to some of the most commonly used items from there. An example is http://underscorejs.org/#first, which wants you to return the first item in an array. Fairly simple, right?
const first = arr => arr[0]
but what about edge cases? What if you pass a string? Or an empty argument? Then once you've grasped the easier ones, you can attempt some of the functions found under 'Collections'. This is a solid way to learn Vanilla JS.
After that, I focused on learning React and building my actual projects with React as my front end library. Hope that helps, feel free to ask any questions.
Edit: https://github.com/waterlink/Challenge-Build-Your-Own-Array-In-Js is also an interesting way to learn, but might be a little too tough at first.
For many trivial examples see underscore.js library API: http://underscorejs.org/ All these functions work on any javascript objects, including those that are unaware of the underscore library. If you do _.where(myFooables, {foo: 'bar'})
, you don't need to prove to the compiler that myFooable
has a possibly optional property foo
which can be a string. Depending on the type system you would need some boilerplate to express this if you're even able to do this.
Meanwhile, as a developer I know that myFooable has the foo property. It's obvious to me, yet unfortunately not guaranteed by anything other than my own discipline or an excessive amount of tests.
The where
function example is one of the easier ones, others like omit
could be even harder to type in a static type system.
As another example – cycle.js just because that's what I've been suffering with recently (making an interface for it in scala.js). If you look at code samples in https://cycle.js.org/getting-started.html you'll see the app uses the DOM
key on seemingly unrelated objects – drivers, sinks, sources. As a developer I know that if I provide a DOMDriver on the DOM
key, a DOMSource will be present on sources at the DOM
key, and I need to write a DOMSink value to the DOM
key in sinks if I want to send that value back to the DOMDriver. This kind of weird distributed typing constraint is natural for javascript developers, but is hard to encode in Scala's type system.
One way of minimizing the calls to elasticsearch is to add a delay between when the user types, and when the ajax request is made. Then, if the user types another character, the delay is reset. This way, an ajax request isn't made until the user stops typing for X amount of time.
While this is neat.. I feel that Underscore.js and/or Lo-Dash adequately (and more importantly pragmatically and readably) support functional-style programming.
For namespacing, modularity and asynchronous script loading in one, you most certainly want to use require.js. Its so called AMD (Asynchronous Module Definition) module format is quickly becoming the standard in client-side JS module systems - an increasing number of open-source libraries support it (including frameworks like the Dojo Toolkit). require.js loads all modules asynchronously, and every module is automatically namespaced. You should really look at the documentation, it is very good and also discusses the rationale behind the system's design.
As to inheritance support, how about Prototype.js? The library has some overlap with jQuery, but its Class.create() functionality is probably just what you are looking for. It also offers some other neat extensions to the JS core classes which are worth using.
Another alternative would be _.extend() from underscore.js.
Hmmm it depends on what language you are interested in and what concepts you want to learn.
I also recommend reading relatively short codebases, because reading codebases with like 100,000 lines of code will result in you trying to navigate the codebase for days with very little returns in proportion to the amount of stress and headaches incurred.
For functional programming in JavaScript, I highly recommend reading underscore.js. It is only roughly 1500 lines long and you will learn a lot by just reading it.
Hope this helps :)
I don't disagree with you actually, but I think we reach different conclusions. Everything is a tool and I think it's important to pick the right tool for the job.
A better example (that I see all of the time) is something like this: "I'm struggling to use selenium to scrape a page, but it's really difficult".
And the solution (often) is: "You should use requests and hit their API directly".
I'm not saying selenium is bad (many times it is definitely the best option), I'm saying that you should look at what you are trying to do, and pick from all of the tools available.
To your second point, I don't think Python has to worry about the JS-ecosystem problem. (That article is one of my favorites and it's sooooo True). For one, Python is a well designed language (IMHO) so it doesn't have to rely on crazy polyfills and extensions (underscore.js is a perfect example of something that doesn't need to exist in Python).
Also, I think that avoiding using python for stuff that it's not well suited for is actually better for the health of the language. There are projects that try to be a full ui framework (like: sofi) or even transpile python to js (http://transcrypt.org/ - that page should tell you all you need to know).
If python for some reason embraced that as a language and tried to be the language for the web/guis, it would probably fall apart as it creates tons of ugly hacks to try to work around a paradigm it was never made for.
I have a lot of issues with JS that I don't have with Python. In fact, I'll still choose Python for the backend even though JS has options available that might integrate with the front end more fully. But when it comes down to it, I'll still pick JS for GUIs because it feels like a better fit for the problem to me.
What you've been asked to do is not really great. In fact, it's pretty bad.
The best thing about it is getting rid of loops. Loops are error-prone (fenceposts, which I still usually get wrong the first time). They also disrupt a declarative programming style, although that hardly matters if everything else isn't declarative already. Pattern matching, on the other hand, is hands down my favorite language feature anywhere.
But as soon as one starts programming functionally, one should take advantage of functional combinators. I.e., functions that operate on other functions. You are creating one in this snippet, but the example given is splicing together everything itself in the body. Instead, you could be using more general combinators. In psuedocode, I would write:
function createStuff(createFunction, howManyTimes){ return enumFromTo(0,howManyTimes).map(createFunction); }
As you can see, this is so simple that it shouldn't even be wrapped into "createStuff". Just use map directly.
The reason this is pseudocode is that JavaScript doesn't have a nice way to
create arrays (like Haskell's [0..howManyTimes]
). You could use
underscore.js' times though, or create
your own utility function. It would be a low-level function that does use
a loop, but you'd only have to get the fenceposts right once and never
worry about it again. :)
If you're set on the object literal notation, you'll need a helper function to copy the properties from the object you're defining into the prototype object. Some examples:
.
Object.assign(myObj.prototype, { where: 'here', there: 'everywhere' })
There's technically nothing bad about it, since its encapsulated in its own scope, but _
is used by two very popular libraries lodash and underscore.
As far as I can see, you're just using it to shorthand this
, not fix this
references. It's needless, and adds confusion to the code.
If you need to fix this
references, the standard is var that = this
, or var self = this
.
It is not the end of programming life. What is more important is the transferable skill in functional programming that Haskell gives:
Other skill that I learned in Haskell is how to purify impure languages like Python, for example:
instead write:
lst = [1, 2, 3, 4]
lst.reverse()
x = lst
create:
def reverse(alist): newalist = alist.copy() newalist.reverse() return newalist
now there is a pure function.
x = reverse(lst)
It is also important to notice that as Haskell uses lazy evaluation by default, in impure languages generally use eager/strict evaluation by default like Python. Higher Order functions needs to be implemented in two ways in impure languages, for Lists (Strict evaluation) and for Generators ( Lazy evaluation).
Besides python and other languages, Javascript can also be programmed in FP style with underscore js. This library is a nice example of implementation of Haskell features in impure languages.
The docs for underscore.js are a good resource for understanding this stuff better.
It's hard to talk about this in the abstract - there are a million articles and tutorials about how these things work, and you can search them as well as I can. You say that you have trouble integrating them into your code - want to make a JSFiddle or something where you suspect these techniques might help, but you're not sure how?
I find libraries like Underscore and/or Lo-Dash to be highly useful. They're effectively just a collection of very useful functions that have some light integration. As a newcomer to javascript, you should browse Underscore's annotated source code and get a feel of what a well put together module looks like.
Angular is awesome but it's kinda hard to learn and you pretty much have to dive head first into it. If you're looking for something cleaner than jquery but not quite as intense as angular, I'd recommend checking out underscore.js templates. You can put your various html templates in script tags and then render them with underscore and js object literals as your data objects. here's a good tute: http://www.bennadel.com/blog/2411-using-underscore-js-templates-to-render-html-partials.htm
This is a good start, the only thing I'd nitpick is that the "var app = app || {};" bit is useless except in the very first JS file (utilities.js).
You say in a comment that you don't like dependencies, but realize that if you go this road you'll probably spend more time doing tech stuff than working on gameplay. Like you'll quickly spend a while setting up the basic "game loop", add in double buffering to avoid flickering, develop your own functions to support classes & inheritance, etc. Not to mention things like resources pre-loading, collision management, or performance optimization. Also, you'll probably implement them worse that if you used a library, so while it's indeed a good exercise for learning, if you want to make a "big-ish" game with several contributors and a lot of code it's probably not the right way to go.
If you change your mind, but want something minimal to work with (as in "so minimal I can easily read the code to understand how it works"), I suggest :
Also, to make the code base more scalable, you can give a try to:
Whatever you choose, have fun making your game :)
Implementing something like this without some kind of throttle mechanism is pretty dangerous.
It is an extremely common situation where your app encounters an error that will result in it throwing an exception or exceptions frequently. Like every frame or every mouse move event etc.
If an app gets deployed where an error of this nature is prevalent, then you can end up DDoS-ing your webserver from customers spamming exception reports to you 60 times a second.
A truly robust solution should batch exceptions together, perhaps scan for duplicates and use something like http://underscorejs.org/#throttle to make sure that clients won't end up overloading your server incase an unexpected, frequently thrown exception loop occurs.
I'd do it like this:
const { apple: apples, orange: oranges } = groupBy('type', test)
console.log(apples) console.log(oranges)
const hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty)
function groupBy (prop, collection) { return collection.reduce((result, target) => { if (hasOwnProperty(target, prop)) { const value = target[prop] result[value] = (result[value] || []).concat([target]) } return result }, {}) }
Most utility libraries already include a groupBy
implementation (Underscore, Lodash, Ramda) - most of them actually support a function as the "prop" parameter, allowing more complex grouping logic.
I don't think the style matters much. What's important is comprehensive text and good examples. If you're good at writing even a flat column of text will be more informative than any elaborate interactive wiki type system. For example Requests has a good documentation, not because they use some trying-to-be-smart system but because it is simply a well structured, well worded text.
PS: Some JavaScript libraries have annoted source which I really like. But it only works for small projects and I don't know if it exists for Python.
JavaScript actually has a very popular library called "underscore" everything is accessed via the _ object.
There is also a competing library called Lodash.... underscore is still more popular for reasons obvious.
Below I'll be using jQuery and Underscore.js. First you'll have a template, either included on your page inside a <script id="projects_rows_template" type="text/template">
tag or included externally with something like RequireJS and its text plugin, and this template will be parsed by Underscore.js' .template
method. Your template will be html
of the new row you'll want to add, like so...
<div class="your-row"> <div class="your-col1"> <img src="<%- image %>"/> </div> <div class="your-col2"> <p class="your-name"><%- name %></p> <p class="your-description"><%- description %></p> </div> <div class="your-col3"> $<%- money %> </div> </div>
...and when you need to add a new row, invoke a function (probably after you submit
the modal form) like this...
function add_project_modal_submit(image,name,description,money){
var template_text=$('#projects_rows_template').html();
$('#projects_rows').append( _.template(template_text)({ 'image':image, 'name':name, 'description':description, 'money':money }) );
}
...and the#projects_rows
above will of course be your container and template_text
will be a string of your html
template. So... your modal submits and passes the new project data to a function like above and Underscore.js will insert that data into a new row to the page. That function can also validate inputs, communicate with your back-end server, etc.
When I want to do a bunch of async operations in parallel and perform some action when they've all completed, I use the parallel tool in the extremely handy async library.
The way I do it is I make an array, and then load the array with one-off functions that do the tasks I want, each completing with a call to callback. I also like to use the even handier underscore when iterating through arrays or objects.
Something like this:
var parallel = [];
//first load up parallel with functions that will make all the api calls we want to make _.each(items, function(item) { parallel.push( function (callback) { makeSomeApiCall( parameters, api_callback(api_results) { callback(api_results); }); }); });
//now execute all of those operations simultaneously //when they're finished, all of their individual results will be in the results array async.parallel(parallel, function(err, results) { _.each(results, function(result) { //do whatever with the result from the api call }); });
Underscore has loads of helpful array methods, such as intersection.
If you're curious about the algorithm, I would give it some thought before you jump to using a previous implementation. The annotated unscorejs source does have the _.intersection
method defined for you to study if you get stuck.
Cool thanks!
I'm considering adding configurations for the controls where delays on keypresses and speeds can be configured.
Thanks for the tip for the randomizer! Right now I'm using the built in 'random' of underscore - which is not very random at all!
Read the annotated Underscore source for their _.debounce(func, wait, immediate)
implementation.
Work through that until you understand it. Its only internal dependency is _.now()
which is stupid-easy to implement yourself (Date.now()
), so feel free to copy the debounce code and play with it yourself.
This is one of the better ways to deal with events that fire a million times per second like scroll events sometimes do.
Underscore's source is easier to read (partly the format, partly the actual code)--I'd start there. Actually, comparing the implementations of particular functions would be a VERY good exercise.
If you really want to get into the nitty gritties do things like
this
works ever again.If you're feeling ambitious try your hand at a simple MVC library. You'll probably be able to use the libraries you've developed above to accomplish it, and that's always pretty cool.
Doing the above are not only good exercises, but will give you a deeper understanding of what's going on behind the scenes with some of the magic you see in the other libraries you use. This will in turn make it feel less like you're not using vanilla javascript when you're using someone else's libraries and give you great insight on when and why it's a good idea to use other peoples libraries or frameworks.
There is nothing necessarily wrong about what you are doing. One issue you might run into along the way is managing the SQL statements as strings, it can get messy. Personally I store my SQL as template files and render them using underscore.template. As for using bluebird, I really don't know, as I've never used it.
There's a lot of reasons to use different languages, and lots of reasons not to. To be a good developer, I think you need to find the balance between those. Programming to me is a way of thinking more than it is knowledge of some specific syntax or framework.
I like /u/oefig's comment that each language has it's own personality, because it's absolutely true. Learning different languages helps you find your own style, and teaches you new ways to do things in languages you already know. Seeing how python does something might influence your PHP programming, or learning a funcational language like Scala/Haskell/F# might even cause you to radically change how you structure a project.
The counter argument though is that if you have a real project, with real deadlines, it makes sense to use what you know.
Beyond that, yes, some languages do things that others cannot, but for general purpose programming, that's rarely a concern. As an example, here's the solution to the first Euler problem in classic C#, in C# with LINQ, and F#.
C#:
int total = 0;
for (int i = 0; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { total += i; } }
C# with LINQ:
var total = Enumerable.Range(1, 999).Select(x => x % 3 == 0 || x % 5 == 0 ? x : 0).Sum();
F#:
let total = [1 .. 999] |> List.filter (fun x -> x % 3 = 0 || x % 5 = 0) |> List.sum
They all accomplish the same thing, but with a very different style and readability. Learning LINQ might cause you to start to program more functionally in say, Javascript with underscore.js
tldr: C# is the best.
In Object Oriented Programming, the general preference is to use composition over inheritance. What this means is that your objects should be made of other objects, instead of subclasses of other objects. In the example of a game having entities and then monsters deriving from that, you'll instead want Monsters that is made from entity parts. Luckily with javascript, we can literally copy those parts from one to the next. To make your life easier, this is a well established pattern present in many frameworks and libraries. For instance, in Underscore, it's called _.extend.
So, build classes from parts, and then use Object.create to produce instances of a class. Don't use inheritance between classes.
I'll point it out before someone gets snarky about it, but I'd consider passing your code to a debounce (or throttle) function. It's not a terribly huge function, but if you don't want to fuss around, you can use something like Underscore JS.
The TL;DR for the what/why for debounce: Your function is executing over and over whenever a scroll event occurs on the window - you only need it to execute at the break point (200px). Debounce will delay the execution of the code until a set time after the event is no longer detected (ie. 100ms after the visitor stops scrolling), while throttle will simply limit the polling to once every set amount of ms. It may seem like overkill, but every little bit helps to make for a smooth experience.
I would recommend looking at the source code for Underscore's <code>_.where</code> function. Here's how the API works:
var guests = [{ name: "Jimmy", food: "pizza", drink: "juice" }, { name: "Kimmy", food: "salad", drink: "water" }, { name: "Timmy", food: "pizza", drink: "water" }];
var pizzaGuests = _.where(guests, { food: "pizza" });
console.log(pizzaGuests); // [ { name: "Jimmy", ... }, { name: "Timmy", ... } ]
console.log(pizzaGuests[0].name); // "Jimmy" console.log(pizzaGuests[0].food); // "pizza" console.log(pizzaGuests[0].drink); // "juice"
var pizzaNames = _.pluck(pizzaGuests, "name");
console.log(pizzaNames); // [ "Jimmy", "Timmy" ]
~~That's awesome where indices aren't necessary, but they're sometimes useful.~~ Nevermind, it seems to pass the index to the iterator, so that's covered. Out of curiosity, why _.each
when forEach
exists? I assume that it's because forEach
is an Array
method, where _.each
seems to support any collection-like object. Not entirely clear on what constitutes a collection-like object. Nor what a context
is. Assumably an object to be used as this
.
I shouldn't have to make these kinds of assumptions when reading the official docs. Colour me unimpressed. "Delegates to the native forEach function if it exists..." or what? Do I really have to go read all of the code? I assume that some interface is relied upon (calls some method), but it doesn't say.
Why not just have the function also call checkValidity at the end? Also, I would definitely look into something like debounce in the underscore library as a great solution to your main problem.
All
: there is <code>Array.prototype.every</code>... Though you might be favoring browser compatibility since IE8 and below don't have that method.
Distinct
: your solution is clever but is O(n²) so it wouldn't be appropriate for very large datasets. A more complicated but O(n) solution would be:
var result = lastnames.reduce(function(ws, value) { if (!ws.set.hasOwnProperty(value)) { ws.set[value] = true; ws.values.push(value); } return ws; }, {set: {}, values: []}).values;
Or, if maintaining the order of the results doesn't matter...
var result = Object.keys( lastnames.reduce(function(set, value) { set[value] = true; return set; }, {}) );
GroupBy
: I'd probably return an object instead of an array to be more idiomatic JS.
An alternative to all of these is to use a library like Underscore.js or Lo-Dash, and that's probably to be preferred over rolling your own. (These libraries are much more popular than the Linq-inspired ones you linked to.)
As you say, you might not need a library, but there's very little reason not to use one.
I kind of like using Underscore's <code>chain</code> method so that operations are expressed closer to the actual order in which they're used...
function wordsAndFrequenciesDescending(wordsFrequencies) { return .sortBy(.map(_.keys(wordsFrequencies), function(key) { return [key, wordsFrequencies[key]]; }), _.property("1")).reverse(); }
becomes...
function wordsAndFrequenciesDescending(wordsFrequencies) { return .chain(wordsFrequences) .keys() .map(function(key) { return [key, wordsFrequencies[key]]; }) .sortBy(.property('1')) .reverse() .value(); }
For a {java,coffee}script developer, functional programming concepts have great utility. Using a library like Underscore, I write most of my javascript in functional style using a combination of map
, filter
, reduce
, pluck
, etc. Particularly for CRUD style applications, the paradigm of transforming data functionally is expressive and robust.
In javascript, these functions are implemented in an imperative manner for performance reasons but they provide a pure interface so I don't have to worry about that as an application developer.
Indeed. Array is an instance of Object (Array instanceof Object => true
). Since []
effectively calls an object constructor for a new Array each time, different objects (pointers) are compared. These types of discrepancies are exactly what libraries like http://underscorejs.org/ solve and explain.
This is a little OT, but does anyone know the reason why the _.range
method for both underscore and lodash don't include the last number in the range in the output? It's something I've always wondered.
I think you mean not written in coffeescript. Second this though.
Another similar function that's good to know is debounce. It will wait until some duration has passed since the function was last called, before calling the given function once. In the past I have used it for a search box that auto-searches; the onkeypress handler should be a debounce wrapper around the search function, with a time of maybe 1 or 2 seconds. That way it won't perform a search for every letter the user types, but only when the user pauses for that duration.
So if nikesoccer01 wants to wait til the user stops moving the mouse or til they pause for a moment, then they would use debounce.
Also sidenote for both of you; lodash is said to be better than underscore for various reasons but otherwise they have a pretty identical feature set and are almost fully compatible with each other. I don't know enough to be able to defend one or the other but I reach for lodash in my new projects.
Yea usually when I see forEach
, it's has slightly different semantics.
OP, peek
or tap
is the method I usually see with these semantics
https://ruby-doc.org/core-2.2.0/Enumerator.html#method-i-peek
I use this suite for functional programming in javascript:
If this isn't a class assignment, I'd want to use existing libraries rather than code something new. But whether that library is useful or not, you might find its naming useful. If I'm understanding you right -- taking one property of each object and making a list of just those -- they call what you're doing a "pluck".
Edit: but since you use the word "break down" then that's perhaps not what you're talking about. In which case the pre-written methods I'd use are called transform() or map(). They don't specify that you're simplifying, but that's certainly a thing that can be done with them.
Totally misunderstood the question the first time.
const arr = [ { animation: 2, categories: null, cuisines: [ 'italian' ] }, { animation: 2, categories: null, cuisines: [ 'french' ] } ]; console.log(arr.filter(function (elm) { return elm.cuisines.indexOf('italian') !== -1; }));
This is the solution as I understand it without underscore. Loop though the markers, then filter them to any that contain (indexof is not -1) the food type. If you need more conditions, just add them to the filter return.
If you don't want to/can't use the native array functions, underscore has alternatives.
http://underscorejs.org/#filter
filter_.filter(list, predicate, [context]) Alias: select Looks through each value in the list, returning an array of all the values that pass a truth test (predicate).
http://underscorejs.org/#indexOf
indexOf_.indexOf(array, value, [isSorted]) Returns the index at which value can be found in the array, or -1 if value is not present in the array. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search ... or, pass a number as the third argument in order to look for the first matching value in the array after the given index.
You may be interested in literate programming.
What do you want your sorted result to look like?
If you adapt the JSON data structure first, then you could use a sort function like you propose or if you want to include a library like underscore.js, you could use their sort method to shorten up the code you would need to write.
You can always use instanceof, like [] instanceof Array
.
Alternatively, you can use Object.prototype.toString.call(obj_to_inspect)
, which in the case of an array will return "[object Array]"
. This is what powers underscore.js's _.isArray
, _.isObject
, etc functions (annotated source).
As far as I know, there's no way to do that with vanilla JavaScript, but Underscore.js has an each function that looks like this:
var myArr = [1, 2, 3]; _.each(myArr, function(elem, index) { console.log(elem); console.log(index); });
Underscore might be a bit helpful in easing the transition from Python, but it's probably just as easy to use a C-style for loop (i.e. for (var i = 0; i < array.length; i++)
).
Here are some things that I noticed:
First off please do not ever make a request to a website and parse the html as a source of data. Websites very frequently change their layouts which means that your data source is not reliable. Additionally there are possible legality issues in doing so. Instead use an api such as this one, which is designed for looking up movies. (sg.media-imdb.com
is an api provided by imdb, while m.imdb.com
is not)
Secondly I'd like to introduce you to underscore. Underscore is an amazing utility that personally I think every one that writes javascript should know about. For example your function deleteDuplicates
could be replaced with mArray = _.uniq(mArray);
Its interesting.
Pedantic observations that mean little :
var newGrid = new Array(10);
you could just
newGrid = [];
You use jquery and underscore (it seems), so anyone testing will need these
<script src='https://code.jquery.com/jquery-2.2.1.min.js'></script> <script src='http://underscorejs.org/underscore-min.js'></script>
as well as the div :
<div class="snake-board"></div>
I couldnt get it to move though. It immediately went into game over state. Hitting a / w/ s/ d had seemingly no effect. I slowed down the timer by adjusting snake.speed to 1000 but no dice.
More comments, and a debug message toggle would be nice. Like
var debug = true; ... if(debug) {console.log('died because hit wall');}
etc...
Whyd you go with underscore? I believe all the functionality you get from it is available vie the functional array methods.
Good stuff though, easy to read and follow.
Edit : also, it pollutes the global namespace. Wrap it in a function IMO.
Let's call two adjacent weeks a
and b
. Someone is scheduled back-to-back if that someone exists in both a
and b
. If we think of this problem as sets, the intersection of a
and b
gives you everyone who is scheduled back-to-back.
If this is in JS, you can use underscore.js#intersection. If this is in PHP, you can use array_intersect.
This would work for detection, but building out the schedule should not need this kind of explicit check.
I don't believe it was because of PHP, it's just one of the few non-alphabetic characters than can be used as a single-character identifier in JS (the underscore being another), and they wanted something that was convenient to type (since jQuery is just a convenience library). I believe Prototype.js actually introduced it first.
http://stackoverflow.com/questions/10787342/why-does-jquery-have-dollar-signs-everywhere
With keys?.. like ["type","car","color","red"]
?.. or without ["car","red"]
or maybe even only keys ["type","color"]
. What array are you looking to get? You can also try looking into underscore's abilities.
While I try and utilize vanilla JavaScript whenever possible, the majority of my projects utilize Underscore.js on the client-side (and quite often on the server-side) so these methods are almost a given... yet for the beginning developer, these are important to be aware of and to understand.
Take a look at the underscore.js annotated source and dissect the reduce, map, filter functions and understand why they are written the way they are.
Pull up this guide to functional programming and work through it a few times.
Keep them as named functions. If you ever decide to unit test this code, you can reference the named functions. With anonymous functions, good luck.
I'd suggest looking into underscore.js [npm] or one of its derivatives. You can leverage a lot of functional idioms and its mini templating library.
function checkDupes(cb) { var notClosedIds = _.pluck(issues.notClosed, "issue"), closedIds = _.pluck(issues.closed, "issue"), openIds = _.difference(notClosedIds, closedIds), notClosedIssuesById = _.indexBy(issues.notClosed, "issue");
return cb(null, _.pick(notClosedIssuesById, openIds)); };
var CLOSED_TEMPLATE = _.template( "<dt><%= issue %></td>" + "<dd><%= summary %></dd>" + "<dd><%= description %></dd>"), NOT_CLOSED_TEMPLATE = _.template( "<dt><%= issue %></td>" + "<dd><%= status %></dd>"), LIST_TEMPLATE = _.template( "<h3><%= title %></h3><dl><%= list.join('') %></dl>");
function formatMail(issues, cb) { var closedMessages = _.map(issues.closed, CLOSED_TEMPLATE), notClosedMessages = _.map(issues.notClosed, NOT_CLOSED_TEMPLATE), closedSection = LIST_TEMPLATE({ title: "Closed", list: closedMessages }), notClosedSection = LIST_TEMPLATE({ title: "Not Closed", list: notClosedMessages });
return closedSection + notClosedSection; };
This. I use that a lot too, since I've discovered it on various popular libraries. I've seen it mostly used to normalize or set default values to arguments. Stuff like:
> function doStuff(param1, param2, options) {
> options = options || {};
> ....
> }
EDIT: Here's a bit from the Unsderscore.js src:
> for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
Another one, trickier:
> var length = array && _.max(array, getLength).length || 0;
At that point it gets a bit hard to read though, unless you're used to it.
I have the shittiest memory of all time, but I don't need to remember what a function named "sort", "filter", "combine", "find" does, because it's obvious from the name. Most of these functions do very little (but well) and therefore tend to have simple names and very little to understand. In the case I do get confused, they are all super well documented. Like this: http://underscorejs.org/#find
The tricky part about the "easy to reason about" is that it only really kicks in when things become more complex. A for loop works pretty okay in a very trivial example like this, but when a for loop starts doing a bunch of things it becomes way less readable. In addition, re-use is the big thing. When you do things in a for loop it becomes so garbled up that you might not even see that you're solving multiple problems at the same times, nor that you are re-solving problems that you've already solved multiple times in your program.
If you want to just get the _id
field off of each user document, you could use use Meteor.users.find({}, {fields: {_id: 1}}).fetch()
, which will give you a list of documents that contain just the _id
field. Alternatively, if you've already done a find().fetch()
on Meteor.users
, you could use _.pluck(listOfUserDocuments, '_id')
. (Underscore docs)
Visualization was created using D3.js. I collected the data using /u/GoldenSights's lovely fork of the PRAW library. I also used underscore.js and the Hopscotch tour framework to make my job a little easier.
Not currently smartphone/tablet compatible. :/
I'd suggest starting with Backbone. React will immediately take you back out of javascript due to their transpiled language, and Angular is gearing up for a major overhaul very soon that will basically make any learning obsolete (it's not going to have any backwards compatibility). Ember would also be a good choice.
Along with Backbone, you'll also want to pick up Underscore.js / Lodash.js for their powerful utility library.
What do you mean by "vanilla javascript (intermediate level)"?
Have you used libraries like jQuery or Underscore.js? Have you built any real/complete applications?
Frameworks and libraries exist for a reason. They help you reduce writing common code so you can focus on building your application.
So go write an application and you'll learn why you need a framework. Otherwise you'll end up with your own framework. Either way, you'll learn something new.
Yup, sounds like a good plan!
I do have some ulterior motives for thinking that a new documentation generator is an interesting idea:
It can depend on many existing packages (markdown parsers, pandoc, lucid, etc)
We can enable documentation to be generated independently of being able to build the package, and remove the GHC dependency. This would require custom import parsing / scope resolution / knowledge of package versions, though. It might be interesting to at least separate generation into a generation step followed by name resolution, such that you can at least get some docs even if the package doesn't build.
Use it as a reason to break visual familiarity and go with a prettier visual style
Could try interesting new features:
Anyway, those are just some misc ideas
You say you have Python and Java experience - despite the syntax, JS is a lot more like Python than Java. Think with functions. You can pass functions as arguments, store functions as variables and object values, and even create new functions within functions and return them.
Higher order functions like those in Underscore.js and similar libraries are vital tools for programming in JavaScript.
Examples:
If you open up a debug console on the page, try running these as examples:
_.all(["1", "2", "3"], _.isNumber); // Are all elements numbers? _.all(["1", "2", "3"], _.isString); // Are all elements strings?
_.any([1, 2, null, 4], _.isNumber); // Is there an element that is a number? _.any([1, 2, null, 4], _.isNull); // Is there an element that is null?
If you have a list you need to merge, just pick apart the JSON and traverse to the list, adding the old list onto the new one.
If you need to selectively overwrite an object's keys and values with a newer version (while keeping older values that didn't appear in the new object), use something like Underscore.js's extend function.
var data1 = JSON.parse(json_string_1); var data2 = JSON.parse(json_string_2);
// Old elements in an array var result_arr = data1.a.b.c.d.e.f;
// Elements from the new request var new_arr = data2.a.b.c.d.e.f;
Array.prototype.concat.apply(result_arr, new_arr);
// data1.a.b.c.d.e.f now contains both result_arr and //new_arr appended to it.
If you must validate on every keypress, make sure you add a little delay using _.debounce() or something similar.
I would do it like this, though:
.addClass('error')
)..removeClass('error')
).jQuery and Underscore both ship with no-conflict functions. You can name your library whatever you like and avoid conflicts by providing the same function.
However, I would recommend implementing the AMD pattern so that consumers of your module can use whatever naming convention they like.
.__proto__
is a read only property in some implementations, and it has a giant red deprecation notice on MDN so I wouldn't rely on it for long even if its working in your browser. If the "extends" idea appeals to you, take a look at underscore.js.
Have you considered using a library like Underscore? Methods like filter and where would be very useful to you:
var results = _.filter(movies, function(movie) { return movie.genre === $('#genre').val(); });
Or...
var results = _.where(movies, { genre: $('genre').val(), rating: $('rating').val() });
There's definitely been a huge amount of improvement on the client side frameworks in recent history. Probably mostly due to browsers starting to support more advanced features, and generally not needing to support IE6,7 etc. anymore.
Also, very much agree with CL being a better language than JS. Although, after reading "Javascript the Good Parts" I feel a lot more comfortable with the language. Turns out if you boil it down to a smaller core language, there's an alright language hiding in there. Add a functional library like [UnderscoreJS]{http://underscorejs.org/} and it's pretty pleasant.
Ok then I'd say adding objects to an array would definitely be easier to go IMO. You could even nest an array with in the object.
Var Question1 = { question:"q1...", answers:["a1","a2", "a3"], correct:1} Var array = [question1]
Personally I'd use underscore to shuffle and pluck from the array. Although if your just playing you may build your own. Hope that helps
It's done using JavaScript to adjust string length based on viewport size
If drill down on the title elements you can see the script tags that are used in handlebars, and I can see underscore loaded and ember. It'll be a feature from ember templates
You might want to look at Underscore - it is a very widely used library that contains lots of functions that help you do things like this. For example, it sounds like you need something like this:
var images = ["foo", "bar", "baz", "qux"]; var delays = _.map(images, function() { return _.random(1, 10); });
console.log(imageDelays); // => [9, 4, 8, 3] (random, so YMMV)
_.map(list, iterator)
creates a new array from the list where each value in the new/old arrays are associated by index with some iterator function. We can zip these two arrays together if we want:
var imageDelays = _.zip(images, delays);
console.log(imageDelays); // => [["foo", 9], ["bar", 4], ["baz", 8], ["qux", 3]]
If you'd rather get the result as an object, you can do:
var imageDelays = _.object(images, delays);
console.log(imageDelays); // => {"foo": 9, "bar": 4, "baz": 8, "qux": 3}
Reddit uses underscore, so you can open your browser console and try this out.
Edit: Here's another way you might be able to achieve what you're trying to do:
var images = ["foo", "bar", "baz", "qux"];
.each(images, function(className) { $("." + className).delay(.random(1, 10) * 100).fadeIn(500); });
var i, post; for (i in posts){ post = posts[i]; console.log(post); }
you can also use something like underscore for additional array/collection functions like _.each()
Haha I remember coming up with pretty much the same exact code a few weeks back, and when I showed my friend he told me about deferreds. Also, a function offering the same functionality is available in underscore.
Cool to see someone else come up with it independently.
I always worry when I see developers do $(element).html("<b>" + user_input + "</b>");
. The correct way to convert user-input into HTML is to use one of the many JavaScript templating libraries, such as mustache.js, underscore.js or jquery-tmpl.