How do I turn this into a callback function? - javascript

I'm new to Javascript, and callbacks are blowing my mind a little at the moment. How do I turn the teletyperDiologue function into a callback? The main reason is I want the teletyper to finish it's job before the displayOut function finishes. Thank you in advance for your help.
function displayOut() {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
// Teletyper for Diologue Box
function teleTyperDiologue(string) {
for (let i = 0; i < string.length; i++) {
setTimeout(function() {
diologueBox.innerHTML += string.slice(i, i + 1);
}, 5 * i);
}
}

As an example:
function test(a) { a(); }
function x() { alert('hello'); }
test(x);
in your case:
function displayOut(callback) {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
callback(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
displayOut(teleTyperDiologue);

You can pass functions around like variables and return them in functions and use them in other functions. So, when you pass a callback function as an argument to another function, you only need to pass the function definition.
See example below.
function displayOut() {
console.log("Display Out running...");
}
function teleTyperDiologue(stringParam, callback) {
console.log("Running teleTyper with string param passed of: ", stringParam);
callback();
}
teleTyperDiologue ("Test string", displayOut);

Related

How to execute functions in a for statement?

I've a two function currently, in the future I'll add much more and I want to execute it in a for statement.
Functions :
function load_lvl1(){
current_lvl += 1;
document.getElementById("intro").style.display = "none";
document.getElementById("level1").style.display = "block";
document.documentElement.scrollTop = 0;
document.getElementById("lvl").innerHTML = "Nivelul : " + current_lvl + " | Incercari : " + attemps;
}
function load_lvl2(){
if(attemps <= 1){
document.getElementById('error').checked = true;
document.getElementById("lvl").innerHTML = "Nivelul : " + current_lvl + " | Incercari : " + attemps;
}
How to execute all functions in a for statement like this :
for(int i = 1; i <= 3; i++){
function name[i];
}
Where i is id or number of the function, it need to look like :
function load_lvl1;
function load_lvl2;
...
You can make an array of your functions, and then iterate that array:
let func = [load_lvl1, load_lvl2];
for (let f of func) {
f(); // call it
}

How do i run animation two, only after animation one has completed?

I understand this question has been answered already, but most of them are in jquery. At the moment function one and function two run at the same time. But how do I alter this code so function two only runs after function one has completed its journey to the top of the screen and back down again?
<html>
<head>
<title>JavaScript Animation</title>
</head>
<body>
<script>
function start() {
animation();
animationone();
}
function animation() {
obj = document.getElementById("jbtext");
obj.style.position = "absolute";
obj.style.bottom = "0px";
w = document.body.clientHeight;
goUp = true;
animateText();
}
var obj, w, goUp;
function animateText() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > w) {
goUp = false;
}
if (pos < 0) {
return;
}
setTimeout(animateText, 10);
}
document.addEventListener("DOMContentLoaded", start, false);
function animationone() {
obja = document.getElementById("jbtexta");
obja.style.position = "absolute";
obja.style.left = "10px";
obja.style.bottom = "10px";
wtwo = document.body.clientWidth;
goRight = true;
animatesecond();
}
var obja, wtwo, goRight;
function animatesecond() {
var position = parseInt(obja.style.left, 10);
(goRight) ? position++ : position--;
obja.style.left = position + "px";
if (position > wtwo) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
return;
}
setTimeout(animatesecond, 10);
}
</script>
<p id="jbtext"> first function</p>
<p id="jbtexta"> second function</p>
</body>
</html>
You can use promises in javascript. Promises are a block of code that will run asynchronously and return at a later point in time. It "returns" by calling the resolve method which is an argument of the Promise constructor. You can then chain promises together to accomplish what you need.
function animationOne() {
return new Promise(function(resolve) {
// ... do your logic for the first animation here here.
resolve(); // <-- call this when your animation is finished.
})
}
function animationTwo() {
return new Promise(function(resolve) {
// ... do your logic for animation two here.
resolve(); // <-- call this when your animation is finished.
})
}
animationOne().then(function() {
animationTwo();
})
This is just another way of Peter LaBanca's answer.
I do not enjoy using Promises. Instead, I use async and await
function runFirst() {
//animation
}
async function waitThenRun() {
await runFirst();
//second animation
}
waitThenRun();
I just don't enjoy the idea of Promise. The code above runs waitThenRun(). That function then runs runFirst(), but waits until it has been finished to run the rest of the function. Having setTimeout or other ways of delaying code in runFirst means you should use Promise. (Pure JS)
MDN
How about the following script AnimationOneAndTwo? The script uses setInterval to “run” the animations. To use it create an instance using the factory method createInstance. Then when the condition or conditions to end the first animation are true call on the next method of the instance to start the second animation. Then when the condition or conditions to end the second animation are true call on the end method of the instance. The following snippet includes the definition for AnimationOneAndTwo and its application to your situation. For more details on how I created the function please refer to “How to Run One Animation after Another: A Reply to a Question at Stack Overflow”.
<html>
<head>
<title>JavaScript Animation</title>
</head>
<body>
<script>
/***
* AnimationOneAndTwo
* Copyright 2019 John Frederick Chionglo (jfchionglo#yahoo.ca)
***/
function AnimationOneAndTwo(parms) {
this.id = parms.id;
}
AnimationOneAndTwo.objs = [];
AnimationOneAndTwo.createProcessLogic = function(parms) {
var obj;
obj = new AnimationOneAndTwo({id: parms.id});
AnimationOneAndTwo.objs[parms.id] = obj;
if ("animationStepOne" in parms) {}
else {
throw new RangeError("animationStepOne not found in parms.");
}
obj["animationStepOne"] = parms.animationStepOne;
if ("animationStepTwo" in parms) {}
else {
throw new RangeError("animationStepTwo not found in parms.");
}
obj["animationStepTwo"] = parms.animationStepTwo;
if ("speed" in parms) {
obj.msf_0 = parms.speed;
}
return obj;
};
with (AnimationOneAndTwo) {
prototype.ap = window;
prototype.dc = window.document;
prototype.np = 6;
prototype.nt = 4;
prototype.ni = 7;
prototype.no = 3;
prototype.nn = 1;
prototype.nr = 1; (function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'iE_in_' + ia[j] + ' = function() {\n';
str += ' this.s_in_' + ia[j] + ' = ( this.m_' + pa[j] + ' < 1 ? true : false );\n';
str += '};\n';
eval(str);
}
})([1], [0]);
(function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'iE_in_' + ia[j] + ' = function() {\n';
str += ' this.s_in_' + ia[j] + ' = ( this.m_' + pa[j] + ' < 1 ? false : true );\n';
str += '};\n';
eval(str);
}
})([0,2,3,4,5,6], [0,2,0,2,5,4]);
(function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'fE_in_' + ia[j] + ' = function() {\n';
str += ' this.m_' + pa[j] + ' -= 1;\n';
str += '};\n';
eval(str);
}
})([3,4,5,6], [0,2,5,4]);
(function(oa, pa, ka) {
var str, j;
for (j=0; j<oa.length; j++) {
str = ' prototype.' + 'fE_ou_' + oa[j] + ' = function() {\n';
str += ' this.m_' + pa[j] + ' += 1;\n';
str += '};\n';
eval(str);
}
})([0,1,2], [1,3,2]);
(function(ta, ia) {
var str, j, k, h;
for (j=0; j<ta.length; j++) {
str = ' prototype.' + 'iE_T_' + ta[j] + ' = function() {\n';
for (h=0; h<ia[j].length; h++) {
k = ia[j][h];
str += ' this.iE_in_' + k + '();\n';
}
if (ia[j].length<1) {
str += ' this.s_t_' + ta[j] + ' = true;\n';
} else {
str += ' this.s_t_' + ta[j] + ' = this.s_in_' + ia[j][0];
for (k=1; k<ia[j].length; k++)
str += ' && this.s_in_' + ia[j][k];
}
str += ';\n';
str += '};\n';
eval(str);
}
})([0,1,2,3], [[0], [1, 2], [3, 6], [4, 5]]);
(function(ta, ia, oa) {
var str, j, k, h;
for (j=0; j<ta.length; j++) {
str = ' prototype.' + 'fE_T_' + ta[j] + ' = function() {\n';
for (h=0; h<ia[j].length; h++) {
k = ia[j][h];
str += ' this.fE_in_' + k + '();\n';
}
for (h=0; h<oa[j].length; h++) {
k = oa[j][h];
str += ' this.fE_ou_' + k + '();\n';
}
str += '};\n';
eval(str);
}
})([0,1,2,3], [[], [], [3, 6], [4, 5]], [[], [], [2], []]);
(function(parms) {
var str, j, k, h, i;
var ta = parms.ta;
var pad = parms.pad;
var pat = parms.pat;
var tar = parms.tar;
var tad = parms.tad;
var tav = parms.tav;
for (i=0; i<ta.length; i++) {
j = ta[i];
str = ' prototype.' + ' pEv_T_' + j + ' = function() {\n';
str += ' this.fE_T_' + j + '();\n';
for (h=0; h<tar[j].length; h++) {
k = tar[j][h];
str += ' this.iE_T_' + k + '();\n';
}
str += ' };\n';
eval(str);
}
})({
ta: [0,1,2,3],
tar: [[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3], [1, 3]]
});
prototype.pEv_T_0 = function() {
this.fE_T_0();
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.animationStepOne();
};
prototype.pEv_T_1 = function() {
this.fE_T_1();
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.iE_T_3();
this.animationStepTwo();
};
prototype.ipn = function() {
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.iE_T_3();
};
prototype.im = function() {
var j, h, pa;
for (j=0; j<this.np; j++) {
eval('this.m_' + j + ' = 0');
}
pa = [1,2,3];
for (h=0; h<pa.length; h++) {
j = pa[h];
eval('this.m_' + j + ' = ' + 0);
}
pa = [0,4,5];
for (h=0; h<pa.length; h++) {
j = pa[h];
eval('this.m_' + j + ' = ' + 1);
}
};
prototype.ai_0 = undefined;
prototype.msf_0 = 10;
prototype.mss_0 = 1500;
prototype.ms_0 = prototype.msf_0;
prototype.sp_0 = function() {
if (this.ai_0) { this.ap.clearInterval(this.ai_0); this.ai_0 = undefined; }
};
prototype.st_0 = function() {
if (this.ai_0) { this.sp_0(); }
this.ai_0 = this.ap.setInterval('AnimationOneAndTwo.objs[' + this.id + '].rn_0()', this.ms_0);
};
prototype.rn_0 = function() {
var t;
var et = [];
if (this.s_t_0) {
this.pEv_T_0();
} else if (this.s_t_1) {
this.pEv_T_1();
} else {
if (this.ai_0) {
this.sp_0();
}
}
};
prototype.start = function() {
with (this) {
if (ai_0) { sp_0(); }
im();
ipn();
st_0();
}
};
prototype.next = function() {
if (this.s_t_2) {
this.pEv_T_2();
} else if (this.s_t_3) {
this.pEv_T_3();
}
};
prototype.end = function() {
if (this.s_t_2) {
this.pEv_T_2();
}
if (this.s_t_3) {
this.pEv_T_3();
}
};
}
var aotobj;
function start() {
animation();
animationone();
aotobj = AnimationOneAndTwo.createProcessLogic({
id: 12345
, animationStepOne: animateText
, animationStepTwo: animatesecond
});
aotobj.start();
}
function animation() {
obj = document.getElementById("jbtext");
obj.style.position = "absolute";
obj.style.bottom = "0px";
w = document.body.clientHeight;
goUp = true;
// animateText();
}
var obj, w, goUp;
function animateText() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > w) {
goUp = false;
}
if (pos < 0) {
aotobj.next();
return;
}
// setTimeout(animateText, 10);
}
document.addEventListener("DOMContentLoaded", start, false);
function animationone() {
obja = document.getElementById("jbtexta");
obja.style.position = "absolute";
obja.style.left = "10px";
obja.style.bottom = "10px";
wtwo = document.body.clientWidth;
goRight = true;
// animatesecond();
}
var obja, wtwo, goRight;
function animatesecond() {
var position = parseInt(obja.style.left, 10);
(goRight) ? position++ : position--;
obja.style.left = position + "px";
if (position > wtwo) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
// AnimationOneAndTwo.objs[12345].end();
aotobj.end();
return;
}
// setTimeout(animatesecond, 10);
}
</script>
<p id="jbtext"> first function</p>
<p id="jbtexta"> second function</p>
</body>
</html>

How to implement lambda /anonymous functions in JavaScript

So I am trying to implement a subset of LISP using JavaScript. I am stuck on two things related to lambdas.
How to implement the ability to create a lambda and at the same time feed it the arguments and have it immediately evaluated? For example:
((lambda(x)(* x 2)) 3)
For now I hard-coded this functionality in my eval-loop like this:
else if (isArray(expr)){
if (expr[0][0] === 'lambda' || expr[0][0] === 'string') {
console.log("This is a special lambda");
var lambdaFunc = evaluate(expr[0], env)
var lambdaArgs = [];
for(var i = 1; i < expr.length; i++){
lambdaArgs.push(expr[i]);
}
return lambdaFunc.apply(this, lambdaArgs);
}
Now this works, and if I write the above lambda with the parameter it will evaluate to 6, however, I am wondering if there is any smarter way to implement this?
If a lambda is instead bound to a symbol, for example:
(define fib (lambda(n)
(if (< n 2) 1
(+ (fib (- n 1))(fib (- n 2)))
)))
In this case, the (define fib) part will be evaluated by the eval-loop first, just as if fib was simply being assigned a number:
else if (expr[0] === 'define') { // (define var value)
console.log(expr + " is a define statement");
var newVar = expr[1];
var newVal = evaluate(expr[2], env);
env.add(newVar, newVal);
return env;
}
And the lambda-function is being created like this:
else if (expr[0] === 'lambda') { // (lambda args body)
console.log(expr + " is a lambda statement");
var args = expr[1];
var body = expr[2];
return createLambda(args, body, env);
}
Separate function to create the lambda:
function createLambda(args, body, env){ // lambda args body
function runLambda(){
var lambdaEnvironment = new environment(env, "lambda environment");
for (var i = 0; i < arguments.length; i++){
lambdaEnvironment.add(args[i], evaluate(arguments[i], env));
}
return evaluate(body, lambdaEnvironment);
}
return runLambda;
}
This works fine for lambdas such as:
(define range (lambda (a b)
(if (= a b) (quote ())
(cons a (range (+ a 1) b)))))
(define fact (lambda (n)
(if (<= n 1) 1
(* n (fact (- n 1))))))
For example, (range 0 10) returns a list from 0 to 10.
But if I try a lambda within a lambda, it does not work. For example:
(define twice (lambda (x) (* 2 x)))
(define repeat (lambda (f) (lambda (x) (f (f x)))))
I would expect the following to return 40:
((repeat twice) 10)
But instead, it returns a list looking like this:
function runLambda(){ var lambdaEnvironment = new environment(env, "lambda
environment"); for (var i = 0; i < arguments.length; i++){
lambdaEnvironment.add(args[i], evaluate(arguments[i], env)); } return
evaluate(body, lambdaEnvironment); },10
Any ideas what might be missing here?
Full JavaScript;
//functions for parsing invoice String
function parse(exp) {
return readFromTokes(tokenize(exp));//code
}
function isNumeric(arg){
return !isNaN(arg);
}
function isArray(obj){
return !!obj && obj.constructor === Array;
}
function readFromTokes(exp){
//Create abstract syntax tree
if (exp.length == 0) {
}
var token = exp.shift();
if (token == '('){
var L = [];
while (exp[0] != ')') {
L.push(readFromTokes(exp));
}
exp.shift(); //remove end paranthesis
return L;
} else {
if (token == ')') {
console.log("Unexpected )");
} else {
return atom(token);
}
}
}
function tokenize(exp){
//Convert a program in form of a string into an array (list)
var re = /\(/g;
var re2 = /\)/g;
exp = exp.replace(re, " ( ");
exp = exp.replace(re2, " ) ");
exp = exp.replace(/\s+/g, ' ');
exp = exp.trim().split(" ");
return exp;
}
function atom(exp){
if (isNumeric(exp)) {
return parseInt(exp); //A number is a number
} else {
return exp; //Everything else is a symbol
}
}
function environment(parentEnvironment, name){
var bindings = [];
var parent = parentEnvironment;
var name = name;
function add(variable, value){
console.log("variable: " + variable + " value: " + value);
bindings.push([variable, value]);
}
function printName(){
console.log(name);
}
function print() {
console.log("printing environment: ")
for (var i = 0; i < bindings.length; i++){
console.log(bindings[i][0] + " " + bindings[i][1]);
}
}
function get(variable){
for (var i = 0; i < bindings.length; i++){
if (variable == bindings[i][0]){
return bindings[i][1];
}
}
if (parent != null){
return parent.get(variable);
} else {
console.log("No such variable");
return false;
}
}
function getParent(){
return parent;
}
this.add = add;
this.get = get;
this.getParent = getParent;
this.print = print;
this.printName = printName;
return this;
}
function addPrimitives(env){
env.add("+", function() {var s = 0; for (var i = 0; i<arguments.length;i++){ s += arguments[i];} return s});
env.add("-", function() {var s = arguments[0]; for (var i = 1; i<arguments.length;i++){ s -= arguments[i];} return s});
env.add("*", function() {var s = 1; for (var i = 0; i<arguments.length;i++){ s *= arguments[i];} return s});
env.add("/", function(x, y) { return x / y });
env.add("false", false);
env.add("true", true);
env.add(">", function(x, y){ return (x > y) });
env.add("<", function(x, y){ return (x < y) });
env.add("=", function(x, y){ return (x === y)});
env.add(">=", function(x, y){ if (x >= y){return true;} else {return false;}});
env.add("<=", function(x, y){ if (x <= y){return true;} else {return false;}});
env.add("eq?", function() {var s = arguments[0]; var t = true; for(var i = 1; i<arguments.length; i++){ if (arguments[i] != s) {t = false }} return t;});
env.add("cons", function(x, y) { var temp = [x]; return temp.concat(y); });
env.add("car", function(x) { return x[0]; });
env.add("cdr", function(x) { return x.slice(1); });
env.add("list", function () { return Array.prototype.slice.call(arguments); });
env.add("list?", function(x) {return isArray(x); });
env.add("null", null);
env.add("null?", function (x) { return (!x || x.length === 0); });
}
function createLambda(args, body, env){ // lambda args body
function runLambda(){
var lambdaEnvironment = new environment(env, "lambda environment");
for (var i = 0; i < arguments.length; i++){
lambdaEnvironment.add(args[i], evaluate(arguments[i], env));
}
return evaluate(body, lambdaEnvironment);
}
return runLambda;
}
function evaluate(expr, env) {
console.log(expr + " has entered evaluate loop");
if (typeof expr === 'string') {
console.log(expr + " is a symbol");
return env.get(expr);
} else if (typeof expr === 'number') {
console.log(expr + " is a number");
return expr;
} else if (expr[0] === 'define') { // (define var value)
console.log(expr + " is a define statement");
var newVar = expr[1];
var newVal = evaluate(expr[2], env);
env.add(newVar, newVal);
return env;
} else if (expr[0] === 'lambda') { // (lambda args body)
console.log(expr + " is a lambda statement");
var args = expr[1];
var body = expr[2];
return createLambda(args, body, env);
} else if (expr[0] === 'quote') {
return expr[1];
} else if (expr[0] === 'cond'){
console.log(expr + " is a conditional");
for (var i = 1; i < expr.length; i++){
var temp = expr[i];
if (evaluate(temp[0], env)) {
console.log(temp[0] + " is evaluated as true");
return evaluate(temp[1], env);
}
}
console.log("no case was evaluated as true");
return;
} else if (expr[0] === 'if') {
console.log(expr + "is an if case");
return function(test, caseyes, caseno, env){
if (test) {
return evaluate(caseyes, env);
} else {
return evaluate(caseno, env);
}
}(evaluate(expr[1], env), expr[2], expr[3], env);
} else if (typeof expr[0] === 'string'){
console.log(expr + " is a function call");
var lispFunc = env.get(expr[0]);
var lispFuncArgs = [];
for(var i = 1; i < expr.length; i++){
lispFuncArgs.push(evaluate(expr[i], env));
}
return lispFunc.apply(this, lispFuncArgs);
} else if (isArray(expr)){
if (expr[0][0] === 'lambda' || expr[0][0] === 'string') {
console.log("This is a special lambda");
var lambdaFunc = evaluate(expr[0], env)
var lambdaArgs= [];
for(var i = 1; i < expr.length; i++){
lambdaArgs.push(expr[i]);
}
return lambdaFunc.apply(this, lambdaArgs);
} else {
console.log(expr + " is a list");
var evaluatedList = [];
for(var i = 0; i < expr.length; i++){
evaluatedList.push(evaluate(expr[i], env));
}
return evaluatedList;
}
} else {
console.log(expr + " cannot be interpreted");
}
}
var globalEnvironment = new environment(null, "Global");
addPrimitives(globalEnvironment);
function start(string) {
return evaluate(parse(string), globalEnvironment);
}
var output = function (string) {
try {
document.getElementById('debugdiv').innerHTML = start(string);
} catch (e) {
document.getElementById('debugdiv').innerHTML = e.name + ': ' + e.message;
}
};
Full HTML;
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Script-Type" content="text/javascript">
<title>LISP in JavaScript</title>
<script type="text/javascript" src="lisp.js"></script>
</head>
<body>
<form id="repl" name="repl" action="parse(prompt.value)">
lisp==>
<input id="prompt" size="200" value="" name="prompt" maxlength="512">
<br>
<input type=button style="width:60px;height:30px" name="btnEval" value="eval" onclick="output(prompt.value)">
<br>
</form>
<div id="debugdiv" style="background-color:orange;width=100px;height=20px">
</div>
</body>
</html>
Further thoughts, suggestions and comments are of course also welcome.
Thank you!
You don't inspect the structure of the operand to see if it's a lambda you eval the operand. The standard way of eval is to check if it's primitive type, then check for special forms and macros, then eval the operator and operands before applying.
Just remove the part where expr[0][0] === 'lambda' || expr[0][0] === 'string' is true and instead of just returning the evaluation of the form you need to apply the operand:
else if (isArray(expr)){
const fn = evaluate(expr[0], env);
const evaluatedList = [];
for(var i = 1; i < expr.length; i++){
evaluatedList.push(evaluate(expr[i], env));
}
return fn(...evaluatedList);
}
The createLambda is wrong since you are evaluating the arguments in the wrong environment. This would be correct since the arguments are already evaluated:
function createLambda(args, body, env){ // lambda args body
function runLambda(){
const lambdaEnvironment = new environment(env, "lambda environment");
for (let i = 0; i < arguments.length; i++){
lambdaEnvironment.add(args[i], arguments[i]);
}
return evaluate(body, lambdaEnvironment);
}
return runLambda;
}

Can I do this in JavaScript? Conditional return if arguments not passed

I want to be able to pass this function either a number to return as a factorial or a number and an id for an existing element on the page, so that it can return the number as text inside my specified element. Here is my code:
function factorial(num,id){
var f=1
for (var i=2; i<=num; i++) {
f*=i;
}
if (!id) {
return f;
}
else if (id)
var msg= document.getElementById(id);
return {
msg.textContent = num + "! = " + output;
};
}
}
factorial(5,"message");
Set the element if passed then return unconditionally:
function factorial(num, id){
var f = 1;
for (var i=2; i<=num; i++) {
f *= i;
}
if (id) {
document.getElementById(id).textContent = num + "! = " + f;
}
return f;
}
alert(factorial(5));
alert(factorial(5,"message"));

how to I get rid of undefined(s) and the other problems in my code?

I've tried this a thousand different ways in a thousand different times and my JS code won't come out the way I want it. When I run it in the Mozilla scratchpad, I get "userHand is undefined" and the second printHand shows as undefined, too. Could someone show me where are the errors in my blackjack game?
function Card (s, n) {
var suit = s;
var number = n;
this.getNumber = function () {
return number;
};
this.getSuit = function () {
return suit;
};
this.getValue = function () {
if (number > 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
}
var cardNames = {1:"Ace", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"Joker", 12:"Queen", 13:"King"};
var suitNames = {1:"Clubs", 2:"Diamonds", 3:"Hearts", 4:"Spades"};
var deal = function () {
var s = Math.floor(Math.random() * 4 + 1);
var n = Math.floor(Math.random() * 13 + 1);
return new Card(s, n);
};
function Hand(){
var cards = [];
cards.push(deal());
cards.push(deal());
this.getHand = function () {
return cards;
};
this.score = function () {
var score;
for (i = 0; i < cards.length; i++) {
score = score + cards[i].getValue();
}
for (i = 0; i < cards.length; i++) {
if (score > 21 && cards[i].getValue() === 11) {
score = score - 10;
}
} return score;
};
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
} alert(hand);
};
this.hitMe = function () {
cards.push(deal());
};
}
var playAsDealer = function () {
var playDealer = new Hand();
while (playDealer.score() < 17) {
playDealer.hitMe();
}
this.printHand = function () {
return playDealer.printHand();
};
this.score = function () {
return playDealer.score();
};
};
var playAsUser = function () {
var playUser = new Hand();
this.printHand = function () {
return playUser.printHand();
};
this.score = function () {
return playUser.score();
};
var decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
for (i = 0; decision !== false; i++) {
playUser.hitMe();
decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
}
};
var declareWinner = function (userHand, dealerHand) {
if ((userHand.score < dealerHand.score) || userHand.score > 21) {
return "You lose.";
} else if (userHand.score > dealerHand.score) {
return "You win.";
} else {
return "You tied.";
}
};
var playGame = function () {
var user = playAsUser();
var dealer = playAsDealer();
declareWinner(user, dealer);
console.log("User got " + user.printHand());
console.log("Dealer got " + dealer.printHand());
};
playGame();
You aren't returning nothing on printHand()
I just added the return statement and worked. See this fiddle
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
}
//alert(hand); //remove this alert
return hand; // <----- solution
};

Categories