Computer Hangs on running this javascript code in browser - javascript

I was trying to create a function in JavaScript for practice and the following code doesn't seem to be executing properly or as intended in the browser.The browser just keeps showing the busy sign and the computer literally hangs.Can anyone help me out with thius code or what the problem is:
function recluse() {
return " It is\ncalled Data.\n\nData is made of merely bits, yet it takes complex forms. Control\nconsists only of simple instructions, yet it performs difficult\ntasks. From the small and trivial, the large and complex arise.\n\nThe program source is Data. Control arises from it. The Control\nproceeds to create new Data. The one is born from the other, the\nother is useless without the one. This is the harmonious cycle of\nData and Control.\n\nOf themselves, Data and Control are without structure. The programmers\nof old moulded their programs out of this raw substance. Over time,\nthe amorphous Data has crystallised into data types, and the chaotic\nControl was restricted into control structures and functions.\n\n%% Short Sayings\n\nWhen a student asked Fu-Tzu about the nature of the cycle of Data and\nControl, Fu-Tzu replied 'Think of a compiler, compiling itself.'\n\nA student asked 'The programmers of old used only simple machines and\nno programming languages, yet they made beautiful programs. Why do we\nuse complicated machines and programming languages?'. Fu-Tzu replied\n'The builders of old used only sticks and clay, yet they made\nbeautiful huts.'\n\nA hermit spent ten years writing a program. 'My program can compute\nthe motion of the stars on a 286-computer running MS DOS', he proudly\nannounced. 'Nobody own a 286-computer or uses MS DOS anymore.', Fu-Tzu\nresponded.\n\nFu-Tzu had written a small program that was full of global state and\ndubious shortcuts. Reading it, a student asked 'You warned us against\nthese techniques, yet I find them in your program. How can this be?'\nFu-Tzu said 'There is no need to fetch water hose when the house is\nnot on fire.'{This is not to be read as an encouragement of sloppy\nprogramming, but rather as a warning against neurotic adherence to\nrules of thumb.}\n\n%% Wisdom\n\nA student was complaining about digital numbers. 'When I take the root\nof two and then square it again, the result is already inaccurate!'.\nOverhearing him, Fu-Tzu laughed. 'Here is a sheet of paper. Write down\nthe precise value of the square root of two for me.'\n\nFu-Tzu said 'When you cut against the grain of the wood, much strength\nis needed. When you program against the grain of a problem, much code\nis needed.'\n\nTzu-li and Tzu-ssu were boasting about the size of their latest\nprograms. 'Two-hundred thousand lines', said Tzu-li, 'not counting\ncomments!'. 'Psah', said Tzu-ssu, 'mine is almost a *million* lines\nalready.' Fu-Tzu said 'My best program has five hundred lines.'\nHearing this, Tzu-li and Tzu-ssu were enlightened.\n\nA student had been sitting motionless behind his computer for hours,\nfrowning darkly. He was trying to write a beautiful solution to a\ndifficult problem, but could not find the right approach. Fu-Tzu hit\nhim on the back of his head and shouted '*Type something!*' The student\nstarted writing an ugly solution. After he had finished, he suddenly\nunderstood the beautiful solution.\n\n%% Progression\n\nA beginning programmer writes his programs like an ant builds her\nhill, one piece at a time, without thought for the bigger structure.\nHis programs will be like loose sand. They may stand for a while, but\ngrowing too big they fall apart{Referring to the danger of internal\ninconsistency and duplicated structure in unorganised code.}.\n\nRealising this problem, the programmer will start to spend a lot of\ntime thinking about structure. His programs will be rigidly\nstructured";
}
var para=recluse().split("\n\n");
function reduce(func,length,array)
{
array.forEach(function(c)
{
length=func(length,c);
});
return length;
}
<!---TOP LEVEL FUNCTION FOR PROCESSING A VALUE WITH A FUNCTION AND CREATING AN ARRAY OF TH RESULTS------------>
function map(func,array)
{
var result_array=[];
array.forEach(function(c)
{
result_array.push(func(c));
});
return result_array;
}
<!-------------THE ALGORITHM FOR FINDING THE EMPHASISED TEXT AND THE FOOTNOTES WITHIN THE TEXT---->
function fragmenter(text)
{
var fragments=[];
function indexing(char)
{
var index=text.indexOf(char);
if(index==-1)
{
return text.length;
}
else
return index;
}
function ifAtStart(char)
{
var end=(char,1);
if(end==-1)
{
throw Error("No enclosing "+char);
}
var part=text.slice(1,end);
text=text.slice(end+1);
return part;
}
function normalText(text)
{
var end=reduce(Math.min,text.length,map(indexing,["*","{"]));//to check that the index is within the text only
var part=text.slice(0,end);
var text=text.slice(end);
return part;
}
while(text!="") <!---4------>
{
if(text.charAt(0)=="*")
{
fragments.push({type:"emphasised",
content:isAtFirst("*")});
}
else if(text.charAt(0)=="{")
{
fragments.push({type:"footnotes",
content:isAtFirst("}")});
}
else
{
fragments.push({type:"Normal",
content:normalText(text)});
}
}
return fragments;
}
console.log(fragmenter(para[1]));

There :
while(text!="")
{
// some code that doesn't change "text"
}
There is no way for text to change in the loop so your code can't finish.
If you're trying to iterate over the chars, you may do this :
for (var i=0; i<text.length; i++) {
if (text.charAt(i)=="*")
But I wonder if you missed the fact that when you call normalText(text), the normalText function can't change the variable it has, but only its own. You must share text. A solution is this :
function normalText() // REMOVED text SO IT USES THE ONE OF THE ENCLOSING SCOPE
{
var end=reduce(Math.min,text.length,map(indexing,["*","{"]));//to check that the index is within the text only
var part=text.slice(0,end);
var text=text.slice(end);
return part;
}
while(text!="")
{
if(text.charAt(0)=="*")
{
fragments.push({type:"emphasised",
content:isAtFirst("*")});
}
else if(text.charAt(0)=="{")
{
fragments.push({type:"footnotes",
content:isAtFirst("}")});
}
else
{
fragments.push({type:"Normal",
content:normalText()}); // REMOVED PASSING TEXT
}
}

Related

How to stop all the scripts in a page in javascript?

I am struggling with the fact that the flow of control in javascript is not what I'm used to. Not linear. Sometimes when I test I get the error message "A script is slowing down your browser" at times when everything should be stopped.
I spend ages looking for the bug. This time it was something really silly, a variable which stopped the function when it reached 350 px. Then I added a way to change the speed and sometimes this variable was incremented by 3 at each step. So it never reached 350, it went from 348 to 351.
So I was wondering if there was a "STOP!" command. Something which would leave the display of the web page in its current state but stop all running processes?
Debugger? It just creates a breakpoint, where you can analyse what's going on right now. I know it's not exactly what you're asking about, but it could work for your use case.
Usage
debugger; 😂
Can be used from within console too.
Learn more
https://www.w3schools.com/js/js_debugging.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger
Depending on what you want here, the main answer is "no".
There are a few "hacks" (but they are quite intrusive and unreliable).
A good one (like mentioned in another answer here) is to throw the statement debugger; (that's all). Example:
let eggCount = 0;
function makeEggs(eggCount){
//Stop! The user is eating too much!!!
if(eggCount > 5){
debugger;
}
else{
make_egg("Over-hard");
return eggCount++;
}
}
However, this only works (or at least for chrome) if the console is open.
The second big one is to throw an error in your script (as shown by this post). It's hacky, and you can't have any try...catch loops (if you do then you have to throw an error, so you'd to re-throw that error).
let eggCount = 0;
function makeEggs(eggCount){
//Stop! The user is eating too much!!!
if(eggCount > 5){
throw "Egg overflow!";
}
else{
make_egg("Sunny side up");
return eggCount++;
}
}
The last big thing you can do (as mentioned by a comment here) is to re-write your logic.
From the looks of it, you have something like this:
let eggCount = 0;
function makeEggs(eggCount){
//Stop! The user is eating too much!!!
if(eggCount === 5){
throw "STOP!"
}
else{
make_egg("Over-hard");
return eggCount++;
}
}
Well, what if we did this?
eggCount = makeEggs(eggCount);
eggCount = 6;
eggCount = makeEggs(eggCount);
Since the equals sign checks for if it's just five, you can always bypass it.
This isn't a good idea, so we can re-wire our logic to do this instead:
let eggCount = 0;
function makeEggs(eggCount){
//Stop! The user is eating too much!!!
if(eggCount >= 5){
throw "STOP!"
}
else{
make_egg("Over-hard");
}
}
Now it will stop if it's 5 or greater.
This:
eggCount = makeEggs(eggCount);
eggCount = 6;
eggCount = makeEggs(eggCount);
will still throw the "STOP" error, even though it's greater than 5.
Sometimes, it's as simple as re-writing your logic.
You don't need the big hack-y stuff if it's as simple as just making your program smarter ;)
I've ran into this type of problem before.
I haven't encountered an incident yet where re-writing my logic doesn't help!

Page Object Pattern asynchronous using node.js selenium

I am having a hard time trying to adjust to asynchronous using node.js. I ran into an issue when using selenium-webdriver and the page object pattern. I feel like somethings have to be synchronous when doing automation testing or your tests will fail because you clicked a button before inserting data. I am having an issue similar to this. I want to add an employee and then search for the employee, but the search for employee is performing before add employee.
var employee = new Employee('grimlek', 'Charles', 'Sexton', 'TitleTitle',
'Upper Management', 'Company Admin', 'Contractor', '-7', 'Remote',
'05212016', '3369407787', '3368791234', 'charles#example.com',
'charles.sexton', 'Skype', 'abcdefgh');
driver.get('https://website.com/login')
.then(function() {
//This behaves as intended
loginPage.login('company.admin', 'password') })
.then(function() {
//Add employee
employeePage.addEmployee(employee) })
.then(function() {
//Search for employee after employee is added
employeePage.searchEmployee(employee)});
EmployeePage Object
var EmployeePage = function (driver) {
this.addEmployee = function (employee) {
driver.findElement(webdriver.By.css('button[class=\'btn btn-default\']')).then(function (element) {
//
//Search employee function is done before the line below this
//
element.click();
}).then(function () {
setTimeout(function () {
driver.findElement(webdriver.By.id('employee_username')).then(function (element) {
element.sendKeys(employee.username);
});
driver.findElement(webdriver.By.id('employee_first_name')).then(function (element) {
element.sendKeys(employee.firstName);
});
driver.findElement(webdriver.By.id('employee_last_name')).then(function (element) {
element.sendKeys(employee.lastName);
});
driver.findElement(webdriver.By.id('employee_title_id')).then(function (element) {
element.sendKeys(employee.title);
});
driver.findElement(webdriver.By.id('employee_role')).then(function (element) {
element.sendKeys(employee.role);
});
}, 5000);
});
//
//
//Search employee should occur when the thread leaves the function
//
};
this.searchEmployee = function (employee) {
driver.findElement(webdriver.By.css('input[class=\'form-control ng-pristine ng-valid\']')).then(function(element) {
element.sendKeys(employee.firstName + ' ' + employee.lastName);
});
};
};
module.exports = EmployeePage;
I know that both searchEmployee and addEmployee functions don't return a promise and I am trying to chain them with the .then function. I do believe this is sorta my problem but I need help with how it should be done and not how I can rig it. Should I use callbacks? I have worked on this problem for going on four hours now and I have tried googling and doing research on various topics. If I didn't provide enough code please let me know and I will provide a simplified runnable example.
A laudable goal is to make each test independent. If a change is made to the application (e,g, bug fix) only the impacted test(s) need to be executed. Also, it makes moving to grid thinkable.
But this is difficult to achieve in practice. Your test has to include all tests needed to satisfy the prerequisites.
Cucumber has feature files that include scenarios Each scenario is a test. Scenarios are executed in the order they are listed in the feature file. So one way to organize things is to include all the prerequisite scenarios before your test in a feature file, You can add tag(s) before the Feature statement so that when you execute that tag the entire feature file runs. Perhaps the first scenario resets (a subset of) the database to a know state.
The trick would be to run features in parallel on multiple machines. If you point those multiple clients to the same server beware that the features should not create or update overlapping entities that could collide when written to the database by the server. E.g. "What do you mean that user 'tom' already exists?" Each feature needs to create a unique user name.
The way of approach using cucumber is to divide you steps for every individual operation.
Ex:
Given I am on XYZ Form
And I provide all form details
In above case, for step And I provide all form details you will be including all the fields in step definition and start filling the fields say name, last name, address in single step definition.
Instead of this we should divide the step for every individual field like:
Given I am on XYZ Form
And I provide name details in XYZ Form
And I provide last name details in XYZ Form
And I provide address details in XYZ Form
And then we will be writing 3 step definition which of course will be running sequentially.
You may feel that the typing work got increased and step definitions got increased unnecessarily, but this will actually help you when a field gets removed from the application itself, you will be only needing to delete related step from future file.
More over you can easily test validation for fields by just commenting one of the step in your feature file.
And your code will be more easy to maintain as every steps is working independently.
And of course sequential work will get achieved.

Is it possible to assign function hooks to game objects, e.g. run function on init, death, etc?

I haven't found any way to assign hooks to anything, and if I could it would be very useful. Also, how can I check whether a game object still exists? (i.e. hasn't died of age, and wasn't destroyed by an enemy.)
If you mean via API - not possible yet. But you can change your current state and compare it to memorized previous state of the objects. For example, if some creep name in Memory still presents, but it is gone in Game.creeps, then something happened.
for(var i in Game.creeps) {
var creep = Game.creeps[i];
creep.memory.lastSeenAt = {x: creep.pos.x, y: creep.pos.y};
}
for(var i in Memory.creeps) {
if(!Game.creeps[i]) {
console.log("Oops! Something happened with a creep "+creep.name+" at "+
Memory.creeps[i].lastSeenAt.x+","+Memory.creeps[i].lastSeenAt.y);
}
}
Here is my use case :
Count the number of hostiles (N) in the current room
Count the number of alive guards (C)
If C < N then build another guard
After a while, when using the Room.find(Game.MY_CREEPS), I'll get dead guards aswell. Having to filter them all the time is really painfull, and the global Memory continues to list them. Is there a way to remove dead creeps from the global Memory object ?
[EDIT]
Found this, hope it will help.
for(var i in Memory.creeps) {
if(!Game.creeps[i]) {
delete Memory.creeps[i];
}
}
I run it at the beginning of each tick
I forked the script-samples repository and made my own events handling code - https://github.com/pineapplemachine/script-samples/tree/master/hooks
Using that script you can assign initialization, update, and destruction methods to events rather than having to handle things more obtusely.
I don't think so. The API seems to be focused on developing code for the main game loop, like writing code inside a while(true). But you can make your creeps do something before they die, for example.
I've created a guard module (just like the harvester module you create on the tutorial). The code below should work:
module.exports = function (creep) {
if(creep.hits<=100) { Game.spawns.Spawn1.createCreep([Game.ATTACK, Game.ATTACK, Game.TOUGH, Game.TOUGH, Game.MOVE], "guard2", {role:"guard"}); }
var targets = creep.room.find(Game.HOSTILE_CREEPS);
if(targets.length) {
creep.moveTo(targets[0]);
creep.attack(targets[0]);
} else{
creep.moveTo(Game.spawns.Spawn1);
}
}

About Node's code style

EDIT
thx to all the answers,
and finally I decide to use some tools like Step,
all I need is "flow control" and don't want any thing else which may slow down the performance (I don't know how much exactly it would effect or the effect just can be ignored).
So I just create a little tool for flow control:
line.js
/**
* Create the "next" function
*
* #param {Array} tasks
* #param {Number} index
* #param {Number} last
*/
var next = function(tasks, index, last) {
if (index == last) {
return tasks[index + 1];
}
else {
return function(data) {
var nextIndex = index + 1;
tasks[nextIndex](next(tasks, nextIndex, last), data);
};
}
};
/**
* Invoke functions in line.
*/
module.exports = function() {
var tasks = arguments,
last = tasks.length - 2;
tasks[0](next(tasks, 0, last));
};
usage:
var line = require("line.js");
line(function(next) {
someObj.find(function(err, docs) {
// codes
next(docs);
});
}, function(next, docs) {
// codes
});
Hope this helps.
EDIT END
As all know,
Node's built-in or third-part modules often provides async API,
and using "callback" function for dealing the results.
It's cool but sometimes would code like this:
//some codes
}
}
}
}
codes like this are hard to read.
I know "deferred" library can solve such problem,
Is there any good "deferred" module for Node?
And How is the performance if I code Node with "deferred"?
It is a large problem with Node-based code; you frequently grow "callback pyramids". There are several approaches to dealing with the problem:
Code style:
Use this annoyance as an opportunity to break your code into bite sized chunks. It means you're likely going to have a proliferation of tiny named funcs - that's probably just fine, though! You might also find more opportunities for reuse.
Flow-control Libraries
There are exactly 593.72 billion flow control libraries out there. Here's some of the more popular ones:
Step super basic serial & parallel flow management.
seq is a heavier but more feature-full flow control library.
There's plenty more. Search the npm registry for "flow" and "flow control" (sorry, doesn't appear to be linkable)
Language Extensions
There are several attempts to provide a more synchronous-feeling syntax on top of JavaScript (or CoffeeScript), often based on the concepts behind the tame paper.
TameJS is the OkCupid team's answer to this.
IcedCoffeeScript they've also ported TameJS over CoffeeScript as a fork.
streamline.js is very similar to TameJS.
StratifiedJS is a heavier approach to the problem.
This route is a deal-breaker for some:
It's not standard JavaScript; if you are building libraries/frameworks/etc, finding help will be more difficult.
Variable scope can behave in unexpected ways, depending on the library.
The generated code can be difficult to debug & match to the original source.
The Future:
The node core team is very aware of the problem, and are also working on lower level components to help ease the pain. It looks like they'll be introducing a basic version of domains in v0.8, which provide a way of rolling up error handling (avoiding the common return err if err pattern, primarily).
This should start to lay a great foundation for cleaner flow control libraries, and start to pave the way for a more consistent way of dealing with callback pyramids. There's too much choice out there right now, and the community isn't close to agreeing on even a handful of standards yet.
References:
Mixu's Node book has an awesome chapter on this subject.
There are tons of "deferred libraries". Have a look there http://eirikb.github.com/nipster/#promise and there http://eirikb.github.com/nipster/#deferred. To pick one, it's only a matter of style & simplicity :)
If you really don't like that, there's always the alternative of using named functions, which will reduce the indentation.
Instead of
setTimeout(function() {
fs.readFile('file', function (err, data) {
if (err) throw err;
console.log(data);
})
}, 200);
You can do this:
function dataHandler(err, data)
{
if (err) throw err;
console.log(data);
}
function getFile()
{
fs.readFile('file', dataHandler);
}
setTimeout(getFile, 200);
The same thing, no nesting.
There are some libraries that may be useful in some scenarios, but as a whole you won't be excited after using them for everything.
According to the slowness issues. Since node.js is async, the wrapped functions are not such a big performance consumer.
You could look here for deferred-like library
https://github.com/kriszyp/node-promise
Also this question is very similar
What nodejs library is most like jQuery's deferreds?
And as a final bonus I suggest you take a look at CoffeeScript. It is a language, which compiles to javascript and has more beautiful syntax, since the function braces are removed
I usually like to use the async.js library as it offers a few different options on how to execute the code

Best practices with jQuery form binding code in an application

We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question.
What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed.
Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file?
You should probably look into a framework like knockout.js This way you can just update your models and the forms will update automatically.
Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data.
I don't know what more there is to say - writing UI code for the browser in JavaScript is no different than writing UI code for other types of apps, as far as I am concerned. Build classes and instantiate them as needed, populate them with data, have them throw events, etc. etc.
Am I up in the night on this? :)
EDIT: In other words, yes - do what you are doing, for the most part. I see too many novice JavaScript hackers write a bunch of poorly-cohesive functions that don't appear to be a part of anything specific other than they are all in a single file. Hope that makes sense.
I think there are multiple challanges for you. The first question is how to structure javascript code, i.e. how to build namespaces so that you don't fight name clashes or have to name your functions like
form1validate
form1aftersubmit
form2validate
form2aftersubmit
One of the proven patterns for modules in javascript is to use an anonymous function to build a new naming scope. The basic idea is shon in the following code
(function() {
var foo = 1;
})();
(function() {
if(foo == 1) alert("namespace separation failed!")
})();
I think this blog entry is a good introduction.
The second question you face is how to avoid all the repetition in javascript code.
You have a couple of weapons against this.
functions - this seams obvious but it's often forgotten to refactor common code into functions where it can be done. In you case this will be functions to copy values from the json response into the forms and like that
higher order function - or functions as data - or callback, as they are often called in javascript. These are the mightiest weapon in javascript. In case for form and ajax handling you can use callback to avoid repetition in the control flow of your forms.
Let me construct an example out of my head (using jquery for convinence)
// this is a validator for one form
var form1validator = function() {
if($("input[name=name]",this).attr("value").length < 1 &&
$("input[name=organisation]",this).attr("value").length < 1)
return "Either name or organisation required"
}
// and this for a second form
var form2validator = function() {
if($("input[name=age]",this).attr("value").length < 21
return "Age of 21 required"
}
// and a function to display a validation result
var displayResult = function(r) {
$(this).prepend("<span></span>").text(r);
}
// we use them as higher order functions like that
$("#form1").onSubmit(validator(form1validator, displayResult, function() {
//on submit
...send some xhr request or like that
});
$("#form2").onSubmit(validator(form2validator, displayResult, function() {
this.submit() // simply submit form
});
$("#form1b").onSubmit(validator(form1validator, function(r) {
alert("There was an validation error " + r);
}, function() {
//on submit
...send some xhr request or like that
});
// the validator function itself would be defined as
function validator(formValidator, displayResult, onSubmit) {
var r = formValidator.apply(this)
if(typeof(r) === 'undefined')
onSubmit(this)
else
displayResult(r)
}

Categories

Resources