What is the value of result? - scope

I am wondering what the value of answer will be after calling the outerfunc. Especially interested in the reasoning behind it (e.g. Why is the return value of the innerfunc not replacing the value stored in var x in the global scope? ) Thanks!
var x = 10;
function outerfunc () {
x = 20;
function innerfunc () {
var x = x + 20;
return x;
}
innerfunc();
}
outerfunc();
var answer = x;

Re Why is the return value of the innerfunc not replacing the value stored in var x in the global scope?
Because you created a new var called x inside innerfunc. Try removing the var from line var x = x + 20;

When you declare a local var with same name as a global var, then the global var become invisible in that function.
function innerfunc () {
var x = x + 20; // here there is no global x. so it is NaN
return x;
}
See this
var x = 10;
function outerfunc () {
x = 20;
function innerfunc () {
var x = x + 20;
alert("value of x in innerFun " + x);
}
innerfunc();
}
outerfunc();
alert("global value of x is " + x);

Related

How to make a string shift backward each letter

I am finishing some functions in a flutter project.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = rune--;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
I give it the word wiggle and I expect vhffkd but it keeps giving wiggle
You have to change:
var mutatedRune = rune--;
to:
var mutatedRune = --rune;
Explanation:
rune-- assigns the value of rune to mutatedRune first, then reduces the value by one. It means mutatedRune and rune has the same value.
--rune reduces the value first, then assigns.
Read about Dart arithmetic operators for more details.
You can fix this by moving the -- to the front of rune.. This happens because putting the -- after the variable only updates the variable after that line.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = --rune;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
For size, maybe:
String shiftBack(String input) =>
String.fromCharCodes([for (var c in input.runes) c - 1]);

Calculate the bounding box of STL file with JavaScript

So I am using this npm package: node-stl
And its working great. However the regexp syntax, mathematics and geometrical calculations are somewhat confusing to me. Especially all at the same time.
Basically what I want to achieve is to extend the script to calculate the bounding box of the STL.
Here is the main file that calculates the volume and weight of the STL being parsed/read.
var fs = require('fs');
// Vertex
function Vertex (v1,v2,v3) {
this.v1 = Number(v1);
this.v2 = Number(v2);
this.v3 = Number(v3);
}
// Vertex Holder
function VertexHolder (vertex1,vertex2,vertex3) {
this.vert1 = vertex1;
this.vert2 = vertex2;
this.vert3 = vertex3;
}
// transforming a Node.js Buffer into a V8 array buffer
function _toArrayBuffer (buffer) {
var
ab = new ArrayBuffer(buffer.length),
view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
// calculation of the triangle volume
// source: http://stackoverflow.com/questions/6518404/how-do-i-calculate-the-volume-of-an-object-stored-in-stl-files
function _triangleVolume (vertexHolder) {
var
v321 = Number(vertexHolder.vert3.v1 * vertexHolder.vert2.v2 * vertexHolder.vert1.v3),
v231 = Number(vertexHolder.vert2.v1 * vertexHolder.vert3.v2 * vertexHolder.vert1.v3),
v312 = Number(vertexHolder.vert3.v1 * vertexHolder.vert1.v2 * vertexHolder.vert2.v3),
v132 = Number(vertexHolder.vert1.v1 * vertexHolder.vert3.v2 * vertexHolder.vert2.v3),
v213 = Number(vertexHolder.vert2.v1 * vertexHolder.vert1.v2 * vertexHolder.vert3.v3),
v123 = Number(vertexHolder.vert1.v1 * vertexHolder.vert2.v2 * vertexHolder.vert3.v3);
return Number(1.0/6.0)*(-v321 + v231 + v312 - v132 - v213 + v123);
}
// parsing an STL ASCII string
function _parseSTLString (stl) {
var totalVol = 0;
// yes, this is the regular expression, matching the vertexes
// it was kind of tricky but it is fast and does the job
var vertexes = stl.match(/facet\s+normal\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+outer\s+loop\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+endloop\s+endfacet/g);
vertexes.forEach(function (vert) {
var preVertexHolder = new VertexHolder();
vert.match(/vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s/g).forEach(function (vertex, i) {
var tempVertex = vertex.replace('vertex', '').match(/[-+]?[0-9]*\.?[0-9]+/g);
var preVertex = new Vertex(tempVertex[0],tempVertex[1],tempVertex[2]);
preVertexHolder['vert'+(i+1)] = preVertex;
});
var partVolume = _triangleVolume(preVertexHolder);
totalVol += Number(partVolume);
})
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// parsing an STL Binary File
// (borrowed some code from here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/STLLoader.js)
function _parseSTLBinary (buf) {
buf = _toArrayBuffer(buf);
var
headerLength = 80,
dataOffset = 84,
faceLength = 12*4 + 2,
le = true; // is little-endian
var
dvTriangleCount = new DataView(buf, headerLength, 4),
numTriangles = dvTriangleCount.getUint32(0, le),
totalVol = 0;
for (var i = 0; i < numTriangles; i++) {
var
dv = new DataView(buf, dataOffset + i*faceLength, faceLength),
normal = new Vertex(dv.getFloat32(0, le), dv.getFloat32(4, le), dv.getFloat32(8, le)),
vertHolder = new VertexHolder();
for(var v = 3; v < 12; v+=3) {
var vert = new Vertex(dv.getFloat32(v*4, le), dv.getFloat32((v+1)*4, le), dv.getFloat32( (v+2)*4, le ) );
vertHolder['vert'+(v/3)] = vert;
}
totalVol += _triangleVolume(vertHolder);
}
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// NodeStl
// =======
// > var stl = NodeStl(__dirname + '/myCool.stl');
// > console.log(stl.volume + 'cm^3');
// > console.log(stl.weight + 'gm');
function NodeStl (stlPath) {
var
buf = fs.readFileSync(stlPath),
isAscii = true;
for (var i=0, len=buf.length; i<len; i++) {
if (buf[i] > 127) { isAscii=false; break; }
}
if (isAscii)
return _parseSTLString(buf.toString());
else
return _parseSTLBinary(buf);
}
module.exports = NodeStl;
If anyone could help me with this it would be great. I know and it feels like it simple. That I just need to know max/min of the different directions(x,y,z) and could then calculate the bounding box.
But I do not understand what the max/min for x,y and z is here. Please answer if you have an idea.
I've made a new branch https://github.com/johannesboyne/node-stl/tree/boundingbox could you please verify whether the applied algorithm works?
Best,
Johannes
Edit: If the branch is stable -> works I'll push it into v.0.1.0 (don't know why it is still 0.0.1)

Is a for loops scope unique

I ran into this while performing some technical debt duties. What is the scope of the variable foo ? Is it really "already defined"?
function fn(){
for (var i = 0; i < m.length; i++) {
if(condition)
for (var j = 0; j < m.length; j++) {
var foo = "bar";
}
else
var foo = "fubar"
}
}
UPDATE: The question is about the scope of the variables defined within a conditional block. Since this isn't nested in a function/closure there is no unique scope.
Here is a snippet to illustrate:
var x = "foo",
a = [];
for(var i=0;i<10;i++){
var x = {value:1+i};
a.push(x)
}
document.write("<pre>" +
x.value + "\n" +
JSON.stringify(a,null," ") +
"</pre>"
);
JavaScript only has function scope, not block scope. So your variable foo exists at function level and both assignments refer to same instance.
var m = [ 1, 2, 3 ];
var x = fn(m, true);
WScript.Echo( x );
var x = fn(m, false);
WScript.Echo( x );
function fn(m, condition){
for (var i = 0; i < m.length; i++) {
if(condition)
for (var j = 0; j < m.length; j++) {
var foo = "bar";
}
else
var foo = "fubar"
}
return foo;
}
A variable in JavaScript declared inside an if or for is accessible outside the if or for after the line of code that has the declaration has been run. For instance:
function DoThing() {
for (var i = 0; i < 1; ++i)
var x = 0;
return x;
}
DoThing(); // returns 0;
In the example you provided the variable is declared after reaching the body of the for loop given condition is true, or in the body of the else statement. Since those conditions are mutually exclusive it is never re-declared by that condition alone. The variable will be re-declared by the loop it is within however.
That said the code isn't very nice to read and I would recommend refactoring it to not have a for loop nested within an if statement, and not declare a new variable within both an if and an else, let alone within the body of a for loop.

is there a way to create a instance

Since from co#4.0+ we can use below statement
var fn = co.wrap(fn*)
to convert a generator into a regular function that returns a Promise.
Then I face a problem
a.js
var F = function *(a,b,c){
this.a = yield this.getA(a);
this.b = yield this.getB(b);
this.c = yield this.getC(c);
}
F.prototype.getA = function * (a){
//........
}
F.prototype.getB = function * (b){
//........
}
F.prototype.getC = function * (c){
//........
}
exports.F = F;
how to create a instance in b.js by co .
#Bergi said it`s a bad practice
then I want to ask anthor question
function* F(){
yield this.x = 2;
yield this.y = 3;
}
var obj = {};
var f = F.bind(obj)();
f.next();
f.next();
f.next();
console.log(obj);
// { x: 2, y: 3 }
is it a bad practice ?

Cannot reference objects defined in other files in express

I am making an application using the express framework of node.js. I have to use OOP features like inheritance in my application.
I created a simple class in routes/model folder.
exports.Rectangle = function(x,y)
{
this.x = x;
this.y = y;
}
Rectangle.prototype.getArea = function()
{
return (this.x * this.y);
}
Rectangle.prototype.toString = function()
{
var tmp = "Rectangle " + this.x + " : " + this.y;
return tmp;
}
My routes/index.js is like this:
exports.index = function(req, res){
var RectangleClass = require('./model/Rectangle.js');
var rect1 = new RectangleClass.Rectangle(4,6);
console.log(rect1.getArea());
console.log("Rect: " + rect1);
res.send("hello");
};
When I run the app I get the error: 500 ReferenceError: Rectangle is not defined
The error is shown at the Rectangle.prototype.getArea = function() line in routes/model/Rectangle.js
However, if I copy paste the Rectangle class structure in my index.js file, then it is all working. But I have many classes and I do not want to define them all in one file. How can I reference objects defined in other files?
This is the problem in your initial setup:
exports.Rectangle = function(x, y) {
...
}
Rectangle.prototype.getArea = ...
exports.Rectangle doesn't magically create a variable called Rectangle in the current module, hence the undefined error when you try to use Rectangle.prototype.
There are a couple of solutions:
// one solution
var Rectangle = exports.Rectangle = function(x, y) { ... }
Rectangle.prototype.getArea = ...
// another solution
var Rectangle = function(x, y) { ... }
Rectangle.prototype.getArea = ...
exports = Rectangle;
// yet another solution
exports.Rectangle = function(x, y) { ... }
exports.Rectangle.prototype.getArea = ...
Or the one you found out yourself, although creating such a factory function isn't really necessary :)
This suddenly occurred to me. I used a getter method to create and return a Rectangle object. The following changes were made in Rectangle.js.
exports.getRectangle = function(x,y)
{
var r = new Rectangle(x,y);
return r;
}
Rectangle = function(x,y)
{
this.x = x;
this.y = y;
}
The other methods were left unchanged.
In my index.js file, instead of
var r = new RectangleClass.Rectangle(6,4);
I used
var r = RectangleClass.getRectangle(6,4);

Resources