Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Thanks both.

e: The answer is always 'more functions'.

Newf fucked around with this message at 19:23 on Apr 24, 2015

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Yes it is.

Couldn't leave it alone
JavaScript code:
Function.prototype.limitCalls = function(limit) {
    var total = 0,
        me = this;
    return function() {
        if (total++ < limit) {
            me.apply(me, arguments);
        }
    };
}

function fart() {
    console.log('toot');
}

asd = fart.limitCalls(1);
asd();
Seems to work.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Newf posted:

The answer is always 'more functions'.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.
Is there a good unit test framework for Javascript that will work with Teamcity? Also, whats a good build runner?

If it matters, for now I am planning on using AngularJS, JQuery, and Twitter Bootstrap, and will be pulling data JSON data from a server to do CRUD type stuff. For now I won't be doing any server side javascript for the JSON API, but when I get time I want to check out node.js.

Its been awhile since I checked up on the state Javascript, just been plugging away at C# backend stuff. But holy poo poo, they have really come out with some awesome new poo poo in the past couple of years. I am actually excited to write some web apps again.


Oh yeah, another question.

I wrote a WPF desktop app for our warehouse recently, I am pretty sure I could have done it quicker with a javascript web app. However, a lot of the apps I work with need to talk to thermal printers, which involves opening a simple TCP/IP socket and sending some strings. I also occasionally need to do full page printing with a driver, but its the kinda thing where the system print dialog can't popup since its a high speed shipping line, its just gotta spool it as soon as you click ok. I assume thats the kind of thing that javascript is not capable of?

I think another option is for me to write all that on the server in PHP or C# or whatever, then configure the apps with a station ID and login that would store printer settings, then send those via ajax, and the printer would handle all the printing.

necrotic
Aug 2, 2005
I owe my brother big time for this!
JS in the browser can't do TCP/IP directly, but node or one of the other server-side ones can.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

necrotic posted:

JS in the browser can't do TCP/IP directly, but node or one of the other server-side ones can.

Ok, thanks for the info.

pigdog
Apr 23, 2004

by Smythe

Begby posted:

I wrote a WPF desktop app for our warehouse recently, I am pretty sure I could have done it quicker with a javascript web app. However, a lot of the apps I work with need to talk to thermal printers, which involves opening a simple TCP/IP socket and sending some strings. I also occasionally need to do full page printing with a driver, but its the kinda thing where the system print dialog can't popup since its a high speed shipping line, its just gotta spool it as soon as you click ok. I assume thats the kind of thing that javascript is not capable of?

I think another option is for me to write all that on the server in PHP or C# or whatever, then configure the apps with a station ID and login that would store printer settings, then send those via ajax, and the printer would handle all the printing.
Wouldn't you also need some level of security, lest someone just on the network just opens a socket and prints a million goatse's and / or fake labels? That stuff would belong on a server anyway.

DimpledChad
May 14, 2002
Rigging elections since '87.

Begby posted:

Is there a good unit test framework for Javascript that will work with Teamcity? Also, whats a good build runner?

Mocha and Jasmine are two popular unit test frameworks. I've used Mocha, and I like it. It lets you plug in lots of different assertion libraries for different styles/DSLs. Also check out Selenium and phantomjs for integration/acceptance testing.

As far as build runners, the big ones are Grunt, Gulp, Broweserify, and Webpack. The latter two let you use node-style modules in the browser. This is holy war territory, so check them all out and see which one appeals to you.

pepito sanchez
Apr 3, 2004
I'm not mexican
Does anyone here have experience with Backbone.Marionette?

The company I work for is suddenly giving up on PHP and wants me to rebuild a website with just jQuery, requireJS, Underscore, Backbone, and Marionette. We're using a C# backend and web service.

This question is a bit specific, but the way it works now, a bit crudely, is it immediately retrieves a JSON of a bunch of items to display on the screen with an Ajax call upon document load. I'd like to do the same thing the Marionette way, connecting to the web service, getting the JSON, saving each item as a model and a complete collection, and immediately rendering the complete collection in a view using routing. It seems more elegant and maintainable, but I'm a bit lost on the whole .sync and .CompositeView thing

Hints or help?

hedgecore
May 2, 2004

pepito sanchez posted:

This question is a bit specific, but the way it works now, a bit crudely, is it immediately retrieves a JSON of a bunch of items to display on the screen with an Ajax call upon document load. I'd like to do the same thing the Marionette way, connecting to the web service, getting the JSON, saving each item as a model and a complete collection, and immediately rendering the complete collection in a view using routing. It seems more elegant and maintainable, but I'm a bit lost on the whole .sync and .CompositeView thing

Hints or help?

On the data/service note, this is Backbone in general, not Marionette. Instantiate a model or collection (whether it's a single data object or a set of similar objects, respectively) and call .fetch() on it to GET the data. You can listen to the "sync" event on the model/collection, and upon that event being triggered, show the view.

As for views, Marionette gives you a few different view types... here's an easy way to think about them:
For single models, use ItemViews.
For collections, use CollectionViews or CompositeViews. Both of them need an ItemView so it knows how to render each item. CollectionViews don't have a template. CompositeViews have a template (so maybe you want to include extra text before or after the list of ItemViews, or table headings, or something else that isn't in each individual ItemView but is still related to the collection in general).

For more info, read the docs on those. They're easily digestible and very informative.
http://marionettejs.com/docs/marionette.itemview.html
http://marionettejs.com/docs/marionette.collectionview.html
http://marionettejs.com/docs/marionette.compositeview.html

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

DimpledChad posted:

Mocha and Jasmine are two popular unit test frameworks. I've used Mocha, and I like it. It lets you plug in lots of different assertion libraries for different styles/DSLs. Also check out Selenium and phantomjs for integration/acceptance testing.

As far as build runners, the big ones are Grunt, Gulp, Broweserify, and Webpack. The latter two let you use node-style modules in the browser. This is holy war territory, so check them all out and see which one appeals to you.

Ok, thanks for all the info.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

pigdog posted:

Wouldn't you also need some level of security, lest someone just on the network just opens a socket and prints a million goatse's and / or fake labels? That stuff would belong on a server anyway.

Its all on a private network, internal servers, and the printers are also on said private network. But thats kinda too bad, because that would be pretty awesome if the package label printers just started printing out goatses. I would do that myself if I could somehow claim that hackers musta done it.

I was working late one night and played the sounds from zombo.com on the warehouse intercom system when nobody was around to see what it sounded like. Man, I want to do that during the day soooo drat bad.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Synthesizing functions with lexical scoping threw me for a loop, but I think I understand now.

In the following:

code:

function makeMysteryFunction(makerValue){
      var newFunction = function doMysteriousThing(param){
      	  return makerValue + param;
      };
      return newFunction;
}

var mysteryFunction3 = makeMysteryFunction(3);
var mysteryFunction5 = makeMysteryFunction(5);

console.log(mysteryFunction3(10) + mysteryFunction5(5)) //23
mysteryFunction3 & mysteryFunction5 are examples of closures. They're capturing the environment that results from makeMysteryFunction(3) & makeMysteryFunction(5) being called. Since makeMysteryFunction is returning a function, that returned function (with makerValue) is what is being saved in mysteryFunction(3) & (5).

That is,

code:
var mysteryFunction3 = function doMysteriousThing(param){ return 3 + param}
So at the very end, when I call mysteryFunction3(10), what I'm basically doing is calling

code:
function doMysteriousThing(10){return 3 + 10};

Sedro
Dec 31, 2008
Pretty much. doMysteriousThing is the closure and makerValue is the thing you're closing over.

If makerValue was in an accessible scope (e.g. global) then you could change its value and the behavior of mysteryFunction3 would change. And that would be a real mystery!

qntm
Jun 17, 2009

Sedro posted:

Pretty much. doMysteriousThing is the closure and makerValue is the thing you're closing over.

If makerValue was in an accessible scope (e.g. global) then you could change its value and the behavior of mysteryFunction3 would change. And that would be a real mystery!

Note that doMysteriousThing retains access to makerValue, which means it can change its own behaviour:

code:
function makeMysteryFunction(makerValue){
      var newFunction = function doMysteriousThing(){
          makerValue += 1;
      	  return makerValue;
      };
      return newFunction;
}

var mysteryFunction7 = makeMysteryFunction(7);
console.log(mysteryFunction7()) // 8
console.log(mysteryFunction7()) // 9

var mysteryFunction23 = makeMysteryFunction(23);
console.log(mysteryFunction23()) // 24
console.log(mysteryFunction23()) // 25

console.log(mysteryFunction7()) // 10

pepito sanchez
Apr 3, 2004
I'm not mexican

hedgecore posted:

On the data/service note, this is Backbone in general, not Marionette. Instantiate a model or collection (whether it's a single data object or a set of similar objects, respectively) and call .fetch() on it to GET the data. You can listen to the "sync" event on the model/collection, and upon that event being triggered, show the view.

As for views, Marionette gives you a few different view types... here's an easy way to think about them:
For single models, use ItemViews.
For collections, use CollectionViews or CompositeViews. Both of them need an ItemView so it knows how to render each item. CollectionViews don't have a template. CompositeViews have a template (so maybe you want to include extra text before or after the list of ItemViews, or table headings, or something else that isn't in each individual ItemView but is still related to the collection in general).

For more info, read the docs on those. They're easily digestible and very informative.
http://marionettejs.com/docs/marionette.itemview.html
http://marionettejs.com/docs/marionette.collectionview.html
http://marionettejs.com/docs/marionette.compositeview.html

Thanks. It's a bit overwhelming having to learn completely new and different frameworks in such a short amount of time, but using a decent boilerplate is helping me a lot. In case anyone wants to play with a Marionette/RequireJS from (almost) bare bones but enough code for guidance so far I've found this invaluable. It just misses any kind of example on server fetching and saving.

https://github.com/ajaxray/marionette-boilerplate

Demo in action: http://ajaxray.com/demo/marionette-boilerplate

It's just very nicely structured (and extremely fast) JS, I think. Though after this project I intend on learning how to use it with a pure Backbone router and probably Handlebars templating. Supposedly one of the lead developers on Marionette said AppRouter was a bad idea and might just be deprecated in the near future. Backbone's router really does seem less complicated.

22 Eargesplitten
Oct 10, 2010



Sorry if this is the wrong thread. I made an unpacked chrome extension, and it's only working intermittently. I haven't figured out exactly what makes it work or not work. I am on an enterprise machine that's been locked down enough that I can't use PowerShell scripts, do you think that's related?

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Struggling with the infamous for loop closure problem since I decided it's time I learn closures

code:
function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];
	var i;
  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }
}

setupHelp();

To my understanding, the problem here is the onfocus = function() part is a closure. And these closures will not get the value of i from the for loop, because they take it from their outer function - setupHelp(), where the value of i is always the last iteration.

In fact,

code:
function(){showHelp(item.help}
is an anonymous closure, it's capturing the value of it's outer function the same way that

code:
function foo(x){
	function bar(y){
		return x + y;  //return exits whatever fn it's inside of, that's why you need a return statement with every one
	}
	return bar;
}
function bar() is capturing the value of x from it's outer variable.


Am I in the ballpark?

Raskolnikov2089 fucked around with this message at 00:42 on May 1, 2015

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Raskolnikov2089 posted:

Struggling with the infamous for loop closure problem since I decided it's time I learn closures



Am I in the ballpark?

Think of it this way: when is showHelp actually *called*? When you focus on something, right? Which means your setupHelp has fully executed by then. So now it gets called: oh, I need to know what "item.help" is, let's look up what the value of "item" is right now! Its the value it got set to on the last iteration of your loop.

Lumpy fucked around with this message at 01:05 on May 1, 2015

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Raskolnikov2089 posted:

Struggling with the infamous for loop closure problem since I decided it's time I learn closures

code:
function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];
	var i;
  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }
}

setupHelp();

To my understanding, the problem here is the onfocus = function() part is a closure. And these closures will not get the value of i from the for loop, because they take it from their outer function - setupHelp(), where the value of i is always the last iteration.

In fact,

code:
function(){showHelp(item.help}
is an anonymous closure, it's capturing the value of it's outer function the same way that

code:
function foo(x){
	function bar(y){
		return x + y;  //return exits whatever fn it's inside of, that's why you need a return statement with every one
	}
	return bar;
}
function bar() is capturing the value of x from it's outer variable.


Am I in the ballpark?

Yes, although there's also the issue of hoisting going on: even though var item = ... is inside the loop it's declaration is hoisted to the top of the function. All the functions created in the loop see this same variable and so call showHelp with the same value of item, the one assigned in the last loop iteration.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

Lumpy posted:

Think of it this way: when is showHelp actually *called*? When you focus on something, right? Which means your setupHelp has fully executed by then. So now it gets called: oh, I need to know what "item.help" is, let's look up what the value of "item" is right now! Its the value it got set to on the last iteration of your loop.

I thought it might be something like that, but when I refreshed my page, and queried the dom element (without focusing on anything) the console.dir already showed the last iteration of i.

If it waits to check until I focus on something, then why is the scope value already populated in the node before I trigger anything? Is it just devtools being overly helpful?

HappyHippo posted:

Yes, although there's also the issue of hoisting going on: even though var item = ... is inside the loop it's declaration is hoisted to the top of the function. All the functions created in the loop see this same variable and so call showHelp with the same value of item, the one assigned in the last loop iteration.

It finally clicked after staring at this example and re-reading and re-reading every article I could find on the for loop problem. It's a loving for loop. Despite the brackets, it's not a function. Since it's not a function, it doesn't have it's own scope, so of course a function declared inside of it only has the outer function to go to for it's environment.



Raskolnikov2089 fucked around with this message at 06:36 on May 1, 2015

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Raskolnikov2089 posted:

I thought it might be something like that, but when I refreshed my page, and queried the dom element (without focusing on anything) the console.dir already showed the last iteration of i.

If it waits to check until I focus on something, then why is the scope value already populated in the node before I trigger anything? Is it just devtools being overly helpful?


When you inspect the DOM element, the dev tools needs to know about the onFocus handler, so it evaluates.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Adventures in Closure 2:

I noticed curious behavior in devtools when messing with for loops and small closures:

code:
function whatAmI(xPassed, xval){
    console.log("what am I is: " + xPassed + xval);
}

function checkVariable(){
    var objectArray = [
        {'id': 'email', 'help': 'Email stuff'},   
        {'id': 'age', 'help': 'Your age'},
        {'id': 'name', 'help': 'Your name'}
    ];
        
    for(var x = 0; x < 3; x++){
        var item = objectArray[x];
        console.log("inside the for loop I am " + x);      //x = 0; x = 1; x = 2
        if(x === 3){
            console.log("I hit 3.  Proof: " + x);
        }
    }
    console.log("outside for loop I am " + x);   // x = 3
    return whatAmI(item.help, x);  //still seems to pass objectArray[2]
}

checkVariable();
if x=3 the returned whatAmI, then how is objectArray[x] still being passed as the 2nd index?

Is it because for loops do have a sort of scope of their own, in the sense that x is left at it's final state before the for loop terminated? But only inside the for loop

code:
 var item = objectArray[x];   //x = 2; since for loop terminated when x = 3 < 3 returned false
repl.it here: http://repl.it/mM7/2

**edit Nevermind - I just realized,

code:

var item = objectArray[x]; 

Only ever has the [x] updated when the conditions of the for loop are met.

x = 3 well and good, but

var item = objectArray[x] only gets to two before loop termination

Raskolnikov2089 fucked around with this message at 21:17 on May 2, 2015

PleasureKevin
Jan 2, 2011

I want to make an extremely simple bitmap image maker thing. Basically you click a tile in a 32 x 32 grid and it activates or deactivates that "pixel". Then probably i'll export or do some other crap. Anyway, wondering which canvas framework I should use, if any.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



PleasureKevin posted:

I want to make an extremely simple bitmap image maker thing. Basically you click a tile in a 32 x 32 grid and it activates or deactivates that "pixel". Then probably i'll export or do some other crap. Anyway, wondering which canvas framework I should use, if any.

Why do you need one? The Javascript/HTML/Canvas API is simple enough and not painful to work with. Code for drawing a square on a Canvas is simple standard stuff, and you can get the browser to convert the Canvas contents to a data URL (in whatever image format) for you.

PleasureKevin
Jan 2, 2011

when i made a thing in canvas before i was manually drawing lines and crap and it seemed like a pain in the arse.i tried to make a maze solving bot and failed.

obstipator
Nov 8, 2009

by FactsAreUseless
I haven't used any canvas libraries, but I've heard EaselJS is good. dunno if its good for your use case though.

Also reading/writing pixels is covered pretty well here in native javascript: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas
Just make functions that do the things if you're repeating yourself a lot.

PleasureKevin
Jan 2, 2011

they're not actual pixels, though. they'll be blown up to be oversized, kind of "8-bit" style. sorry should have said that. so actually they'll be, like 8px by 8px rectangles that change from white to black when you click them. anyway i'll just do whatever thanks.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

PleasureKevin posted:

anyway i'll just do whatever

The realization of modern ideals. The birth of a web developer. :woz:

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
As far as I can tell all you need to do is draw squares. I can't imagine a framework making that any easier than it already is.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



PleasureKevin posted:

they're not actual pixels, though. they'll be blown up to be oversized, kind of "8-bit" style. sorry should have said that. so actually they'll be, like 8px by 8px rectangles that change from white to black when you click them. anyway i'll just do whatever thanks.

You could just use a grid of DIVs to do that and only involve the canvas for exporting/saving if you wanted.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Just use a scaled canvas and do some multiplication and division.

huhu
Feb 24, 2006
When you guys are doing pure JavaScript and all you want to see is maybe the results of console.log, what does your work space look like?

Impotence
Nov 8, 2010
Lipstick Apathy
[a@shell ~]$ node file.js
resultofconsolelog

Impotence fucked around with this message at 00:00 on May 10, 2015

huhu
Feb 24, 2006

Biowarfare posted:

node file.js

Could you elaborate in a full sentence?

Ideally, more than "Use node and file.js."

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

huhu posted:

Could you elaborate in a full sentence?

Ideally, more than "Use node and file.js."
'
Node runs javascript. If you have node installed and(set up on your path) and type "node file.js" it will run the file provided on the command line in a node server. Window.console output will be logged to the command line.

If you're not big on node, phantomjs does the same thing.

huhu
Feb 24, 2006

Bruegels Fuckbooks posted:

'
Node runs javascript. If you have node installed and(set up on your path) and type "node file.js" it will run the file provided on the command line in a node server. Window.console output will be logged to the command line.

If you're not big on node, phantomjs does the same thing.

Thanks.

Another question. My first idea for a larger project was to make a "dictionary" that hooked up to the MDN. People could take HTML they wrote, get it processed and have the dictionary terms they knew be marked so they could keep track of what tags and elements they have already learned. I started out building the code for processing a website and have gotten this far and you can see it live here.

I feel like I got pretty far with it yesterday but there's a lot of special cases such as single and double quotes, comments, other languages within an HTML document(such as PHP which I know nothing about yet) and the more I try and tackle these problems, errors start popping up that I'm clueless about their origin.

Did I bite off more than I could chew or is there an end in sight? Luckily, at the very least I learned a ton about dealing with strings.

huhu fucked around with this message at 04:04 on May 11, 2015

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

huhu posted:

Thanks.

Another question. My first idea for a larger project was to make a "dictionary" that hooked up to the MDN. People could take HTML they wrote, get it processed and have the dictionary terms they knew be marked so they could keep track of what tags and elements they have already learned. I started out building the code for processing a website and have gotten this far and you can see it live [url=https://htmlpreview.github.io/?https://github.com/TravisBumgarner/Codesaurus/blob/master/index.html]here.[/url]

I feel like I got pretty far with it yesterday but there's a lot of special cases such as single and double quotes, comments, other languages within an HTML document(such as PHP which I know nothing about yet) and the more I try and tackle these problems, errors start popping up that I'm clueless about their origin.

Did I bite off more than I could chew or is there an end in sight? Luckily, at the very least I learned a ton about dealing with strings.

It looks like you're trying to write an HTML parser in javascript. That... seems unnecessary.

huhu
Feb 24, 2006

Bruegels Fuckbooks posted:

It looks like you're trying to write an HTML parser in javascript. That... seems unnecessary.

Just looked up what a parser was... don't think that's what I'm doing.

My goal was to take this:

code:
<html>
     <head>
          <title>ss</title>
     </head>
     <body>
          <h1>sdfsdf</h1>
          <p>sdfsdf</p>
     </body>
</html>
Turn it into an
code:
array = [body,h1,head,html] 
Compare that array to an array with all html elements.

The end result would be a webapp that interacted with the Mozilla Developer Network that kept track of which HTML tags you've used before, which you haven't used yet, and stats about usage of each. I was going to add support for attributes and maybe some other tools. Its goal was to help as a sort of reference for me, and maybe others, as I learn HTML.

Adbot
ADBOT LOVES YOU

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
If you've got the DOM to work with, you can do stuff like that with jQuery, and it's probably not that hard to make this native java script:
code:
var elements = {}; 
$('*').each(function() { 
	elements[this.tagName] = elements[this.tagName]+1 || 1; 
}); 
console.log(elements);
But Mr. Fuckbooks has a point about processing HTML. You don't want to parse HTML with regex (this way lies madness), and making a parser in JS could be quite an exercise.

That said, if you're only collecting element names (<thing >) and attributes contained in those elements (<thing attr="value">), and you don't actually care about order, validity, standards etc, then you could probably take quite a few shortcuts and nobody would be the wiser.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply