I'm struggling on how to increment a basic counter in javascript.
What do I want to achieve ?
I need a counter inside a foreach loop. The goal is to be able to count each time the //Write smthg is triggered.
Below is the updated version of the code I'm using. For the moment, it returns weird sequences of numbers. I guess it is resetted each time the recursive loop is triggered. I do not know how to correct it, suppose it's a basic javascript problem but as I'm learning through experimenting and on my own, I sometimes need to ask question to the community.
function walk(dir, counter = 0) {
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
counter = walk(fullPath, counter);
walk(fullPath, counter);
console.log('dir');
} else {
let size = fs.statSync(fullPath).size; // Get size of file
listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
++counter;
console.log(counter);
}
});
return counter;
}
walk(copyFrom); // Starts function "walk"
Sequences obtained :
2,3,4,5,6,7,dir,5,6,8,9,10,11,12,13,dir,11
Here is the complete answer
function walk(dir) {
let n = 0;
function walk(dir) {
fs.readdirSync(dir).forEach(file => {
++n;
console.log(n);
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
--n;
walk(fullPath);
console.log('dir');
} else {
let size = fs.statSync(fullPath).size; // Get size of file
listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
}
});
}
return walk(dir);
}
Use a helper. The function walk makes the lexical variable n and a function walk that shadows the called fucntion for the duration of the recursive calls. It may have the original content of walk and the outer function just returns the result of calling it as itself was called.
function walk(dir) {
let n = 0; //Counter variable
function walk(dir) {
dir.forEach(file => {
++n;
console.log(n);
if (true) {
//Recurse loop
} else {
//Write smthg
}
});
}
return walk(dir);
}
So, your issue is as follows:
Your counter will reset to 0 each time you recurse. So your numbers can go something like so: 0, 1, 0, 2, 0, 1, 2, 3, 3, ...etc. If you want to have an iterator counting total number of iterations, you'll need to pass your counter into the function and default it to 0 (for the first time walk is called), like so:
var files = ["dir1-file1", "dir1-file2", ["dir1-sub1-file1"], "dir1-file3", ["dir1-sub2-file1", ["dir1-sub2-subsub1-file1"]]];
function walk(dir, counter = 0) {
dir.forEach(file => {
if (Array.isArray(file)) {
// pass counter in to recursed function call
// set current function counter to the result of the recursed function calls
counter = walk(file, counter);
} else {
//Write smthg
++counter;
console.log(counter);
console.log(file);
}
});
// return the counter for parent
return counter;
}
walk(files);
Related
I have two problems i cant figure out. When i call GetParams first to get used defined values from a text file, the line of code after it is called first, or is reported to the console before i get data back from the function. Any data gathered in that function is null and void. The variables clearly are being assigned data but after the function call it dissapears.
let udGasPrice = 0;
let udGasLimit = 0;
let udSlippage = 0;
I want to get data from a text file and assign it to variables that need to be global. able to be assigned in a function but used outside it. So above is what i was doing to declare them outside the function. because if i declare them inside, i lose scope. It doesnt seem right to declare with 0 and then reassign, but how else can i declare them gloabaly to be manipulated by another function?
next the code is called for the function to do the work
GetParams();
console.log('udGasPrice = " + udGasPrice );
The code after GetParams is reporting 0 but inside the function the values are right
The data is read and clearly assigned inside the function. its not pretty or clever but it works.
function GetParams()
{
const fs = require('fs')
fs.readFile('./Config.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return;
}
// read file contents into variable to be manipulated
var fcnts = data;
let icnt = 0;
for (var x = 0; x < fcnts.length; x++) {
var c = fcnts.charAt(x);
//find the comma
if (c == ',') {
// found the comma, count it so we know where we are.
icnt++;
if (icnt == 1 ) {
// the first param
udGasPrice = fcnts.slice(0, x);
console.log(`udGasPrice = ` + udGasPrice);
} else if (icnt == 2 ) {
// second param
udGaslimit = fcnts.slice(udGasPrice.length+1, x);
console.log(`udGaslimit = ` + udGaslimit);
} else {
udSlippage = fcnts.slice(udGaslimit.length + udGasPrice.length +2, x);
console.log(`udSlippage = ` + udSlippage );
}
}
}
})
}
Like i said i know the algorithm is poor, but it works.(Im very noob) but why are the variables not retaining value, and why is the code after GetParams() executed first? Thank you for your time.
The code is executed before the GetParams method finishes, because what it does is an asynchronous work. You can see that by the use of a callback function when the file is being read.
As a best practice, you should either provide a callback to GetParams and call it with the results from the file or use a more modern approach by adopting promises and (optionally) async/await syntax.
fs.readFile asynchronously reads the entire contents of a file. So your console.log('udGasPrice = " + udGasPrice ); won't wait for GetParams function.
Possible resolutions are:
Use callback or promise
let udGasPrice = 0;
let udGasLimit = 0;
let udSlippage = 0;
GetParams(() => {
console.log("udGasPrice = " + udGasPrice);
});
function GetParams(callback) {
const fs = require('fs')
fs.readFile('./Config.txt', 'utf8', (err, data) => {
if (err) {
console.error(err)
return;
}
// read file contents into variable to be manipulated
var fcnts = data;
let icnt = 0;
for (var x = 0; x < fcnts.length; x++) {
var c = fcnts.charAt(x);
//find the comma
if (c == ',') {
// found the comma, count it so we know where we are.
icnt++;
if (icnt == 1) {
// the first param
udGasPrice = fcnts.slice(0, x);
console.log(`udGasPrice = ` + udGasPrice);
} else if (icnt == 2) {
// second param
udGaslimit = fcnts.slice(udGasPrice.length + 1, x);
console.log(`udGaslimit = ` + udGaslimit);
} else {
udSlippage = fcnts.slice(udGaslimit.length + udGasPrice.length + 2, x);
console.log(`udSlippage = ` + udSlippage);
}
}
}
callback()
})
}
fs.readFileSync(path[, options]) - it perform same operation in sync - you still need to edit your code accordingly
Also, it's advisable that you don't edit global variables in the function and return updated variables from the function.
I have an exercise about JavaScript. This exercise requires me to use higher-order functions. I have managed to specify some of the functions so far, but when I try to execute the code, the result does not seem to work properly. I have some images to give you an idea, hopefully, you can help me correct this.
The thread is: Write the function loop(loops, number, func), which runs the given function the given number of times. Also write the simple functions halve() and square().
This is my code:
function loop(loops, number, func) {
var loops = function(n) {
for (var i = 0; i < n; i++) {
if (i < 0) {
console.log('Programme ended')
}
if (i > 0) {
return n;
}
}
}
}
var halve = function(n) {
return n / 2
}
var square = function(n) {
return n ** 2;
}
console.log(halve(50));
console.log(loop(5, 200, halve));
console.log(loop(3, 5, square));
console.log(loop(-1, 99, halve));
Your current loop function declares an inner function and then exits. Ie, nothing actually happens -
function loop(loops,number,func){
// declare loops function
var loops= function(n){
// ...
}
// exit `loop` function
}
One such fix might be to run the supplied func a number of times in a for loop, like #code_monk suggest. Another option would be to use recursion -
function loop (count, input, func) {
if (count <= 0)
return input
else
return loop(count - 1, func(input), func)
}
function times10 (num) {
return num * 10
}
console.log(loop(3, 5, times10))
// 5000
so first things first: Higher-Order functions are functions that work on other functions.
The reason why you get undefined is because you are calling a function which doesn't return anything.
function x(parameter){
result = parameter + 1;
}
// -> returns undefined every time
console.log(x(5));
// -> undefined
function y(parameter){
return parameter+1;
}
// -> returns a value that can be used later, for example in console.log
console.log(y(5));
// -> 6
Second, you are using n for your for loop when you should probably use loops so it does the intended code as many times as "loops" indicates instead of the number you insert (i.e. 200, 5, 99).
By having the "console.log" inside a loop you may get a lot of undesired "programme ended" in your output so in my version I kept it out of the loop.
The other two answers given are pretty complete I believe but if you want to keep the for loop here goes:
function loop(loops, number, func){
if(loops>0){
for(let i = 0; i< loops; i++){ // let and const are the new ES6 bindings (instead of var)
number = func(number)
}
return number
}
else{
return "Programme ended"
}
}
function halve(n) { // maybe it's just me but using function declarations feels cleaner
return n / 2;
}
function square(n) {
return n ** 2;
}
console.log(halve(50));
console.log(loop(5, 200, halve));
console.log(loop(3, 5, square));
console.log(loop(-1, 99, halve));
Here's one way
const loop = (loops, n, fn) => {
for (let i=0; i<loops; i++) {
console.log( fn(n) );
}
};
const halve = (n) => {
return n / 2;
};
const square = (n) => {
return n ** 2;
};
loop(2,3,halve);
loop(4,5,square);
const _debounce = (n, func) => {
//code here
}
const originFun = () => {
console.log('hit')
}
const _call = () => _debounce(2, originFun)
_call() //The originFun not executes
_call() //hit
_call() //The originFun not executes
_call() //hit
I do not know how to implement it, even after a test.
_debounce should accept the sort argument, and the originFun function, and return its own function (or closure) that you can assign to _call. You can then call _call with it's own argument - the number.
function originFun(sort) {
console.log('hit,', sort);
}
function _debounce(sort, func) {
// Set a counter
let count = 1;
// Because closures retain the variables from the
// preceding lexical environment we can
// still use and update `count` when the function is returned
// This function (which accepts a number argument) is what's
// assigned to _call.
return function(n) {
// Call originFun with the number if the remainder of dividing
// sort by count is zero
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
if (count % sort === 0) func(n);
count++;
}
}
// _debounce returns a function that accepts a number
// argument. We assign that function to _call.
const _call = _debounce(2, originFun);
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4
This implementation of debounce should help your use case. No global variable, and is implemented in pure javascript.
function _debounce(func, n){
let count = 0;
return (...args) => {
count++;
if (count % n === 0) {
count = 0;
func.apply(this, args);
}
};
}
const originFun = (sort) => {
console.log('hit,', sort)
}
const _call = _debounce((sort) => originFun(sort), 2);
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4 */
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4 */
To keep track of the number of calls you could use a global counter.
Additionally, you can pass arguments to your function using the spread syntax. That way you can have multiple arguments and all of them will be passed to the function in order.
let counter = 1;
const _debounce = (n, func, ...args) => {
if (counter === n) {
counter = 1;
func(...args);
} else {
counter += 1;
}
}
const originFun = (sort) => {
console.log('hit,', sort)
}
const _call = (sort) => _debounce(2, originFun, sort)
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4
I have a function that when called will decrease by 1. It is called when a user reports something. I want to be able to store this and then when it hits 0, to execute an action.
function userReported() {
console.log('user report ' + add());
var add = (function () {
var counter = 10;
return function () {
counter -= 1;
return counter;
}
})();
}
Now the problem is I can return the counter so it logs down from 10. But the issue I have is that I can seem to add an if/else before returning counter as it does not store the variable.
I attempted the following but it doesn't work and I don't know how to return something > store it, and at the same time check its value. I also tried a while loop but failed too.
function userReported() {
var limit = add;
if ( limit <= 0 ) {
console.log('Link does not work!');
}
else {
console.log('user report ' + limit);
}
var add = (function () {
var counter = 10;
return function () {
counter -= 1;
return counter;
}
})();
}
How do I go about creating a value, increment/decrement said value, then when it reaches a number -> do something?
You would typically do this with a function that returns a function that captures the counter in a closure. This allows the returned function to maintain state over several calls.
For example:
function createUserReport(limit, cb) {
console.log('user report initiated' );
return function () {
if (limit > 0) {
console.log("Report filed, current count: ", limit)
limit--
} else if (limit == 0) {
limit--
cb() // call callback when done
}
// do something below zero?
}
}
// createUserReport takes a limit and a function to call when finished
// and returns a counter function
let report = createUserReport(10, () => console.log("Reached limit, running done callback"))
// each call to report decrements the limit:
for (let i = 0; i <= 10; i++){
report()
}
You can of course hard-code the callback functionality and limit number into the function itself rather than passing in arguments.
Ok, if you need to get a report based on an external limit, you could do something like that:
var limit = 10;
function remove() {
limit -= 1;
}
function userReport() {
if (limit <= 0) {
console.log("Link does not work!");
} else {
remove();
console.log(`User report: ${limit}`);
}
}
userReport();
If that's what you want, removing the remove function from userReport and taking the limit variable out will make things work
I am trying to create a page which needs to preform lots of loops. Using a while/for loops cause the page to hang until the loop completes and it is possible in this case that the loop could be running for hours. I have also tried using setTimeout, but that hits a recursion limit. How do I prevent the page from reaching a recursion limit?
var looper = {
characters: 'abcdefghijklmnopqrstuvwxyz',
current: [0],
target: '',
max: 25,
setHash: function(hash) {
this.target = hash;
this.max = this.characters.length;
},
getString: function() {
string = '';
for (letter in this.current) {
string += this.characters[this.current[letter]];
}
return string;
},
hash: function() {
return Sha1.hash(this.getString());
},
increment: function() {
this.current[0] += 1;
if (this.current[0] > this.max) {
if (this.current.length == 1) {
this.current = [0, 0];
} else {
this.current[1] += 1;
this.current[0] = 0;
}
}
if (this.current[1] > this.max) {
if (this.current.length == 2) {
this.current[2] == 0;
} else {
this.current[3] += 1;
this.current[2] = 0;
}
}
},
loop: function() {
if (this.hash() == this.target) {
alert(this.getString());
} else {
this.increment();
setTimeout(this.loop(), 1);
}
}
}
setInterval is the usual way, but you could also try web workers, which would be a more straightforward refactoring of your code than setInterval but would only work on HTML5 browsers.
http://dev.w3.org/html5/workers/
Your setTimeout is not doing what you think it's doing. Here's what it's doing:
It encounters this statement:
setTimeout(this.loop(), 1);
It evaluates the first argument to setTimeout, this.loop(). It calls loop right there; it does not wait for a millisecond as you likely expected.
It calls setTimeout like this:
setTimeout(undefined, 1);
In theory, anyway. In reality, the second step never completes; it recurses indefinitely. What you need to do is pass a reference to the function rather than the returned value of the function:
setTimeout(this.loop, 1);
However, then this will be window on the next loop, not looper. Bind it, instead:
setTimeout(this.loop.bind(this), 1);
setInterval might work. It calls a function every certain amount of milliseconds.
For Example
myInterval = setInterval(myFunction,5000);
That will call your function (myFunction) every 5 seconds.
why not have a loop checker using setInterval?
var loopWorking = false;
function looper(){
loopWorking = true;
//Do stuff
loopWorking = false;
}
function checkLooper()
{
if(loopWorking == false)
looper();
}
setInterval(checkLooper, 100); //every 100ms or lower. Can reduce down to 1ms
If you want to avoid recursion then don't call this.loop() from inside of this.loop(). Instead use window.setInterval() to call the loop repeatedly.
I had to hand-code continuation passing style in google-code prettify.
Basically I turned
for (var i = 0, n = arr.length; i < n; ++i) {
processItem(i);
}
done();
into
var i = 0, n = arr.length;
function work() {
var t0 = +new Date;
while (i < n) {
processItem(i);
++i;
if (new Date - t0 > 100) {
setTimeout(work, 250);
return;
}
}
done();
}
work();
which doesn't hit any recursion limit since there are no recursive function calls.