how function numberIterator - javascript

help me to solve this with recursive
how number five is not hardcode
function numberIterator(num) {
var number=num
if (number==0) {
return 5
}
var first=5
var temp=""
temp+= first -(number)
return temp+numberIterator(num-1)
}
console.log(numberIterator(5)); // '012345'
// console.log(numberIterator(7)); // '01234567'

Here are three implementations.
function numberIterator1(num) {
function helper(cur, acc) {
return cur > num ? acc : helper(cur+1, acc + cur);
}
return helper(0, '');
}
function numberIterator2(num) {
return Array.from(Array(num+1).keys()).join('');
}
function numberIterator3(num) {
let str = '', cur = -1;
while(++cur <= num) str += cur;
return str;
}
console.log(numberIterator1(5)); // '012345'
console.log(numberIterator2(5)); // '012345'
console.log(numberIterator3(5)); // '012345'
console.log(numberIterator1(7)); // '01234567'
console.log(numberIterator2(7)); // '01234567'
console.log(numberIterator3(7)); // '01234567'

Related

i want to make a search in which i can search upper case and lower case both at same time..?

the problem statement is i have to make a search function in which i can search lower can upper case element both even if i type lower case either upper case
i tried upper case search and lower case but its not working at all please suggest me as soon as possible
search(searchValue) {
if (searchValue != null && searchValue != "") {
var searchItem = searchValue;
var allOppData = this.stagesWiseOpportunitiesData;
var filtered = _.mapValues(allOppData, statuses =>
_.filter(statuses, statusT =>
_.some(statusT, T => _.includes(T, searchItem))
)
);
this.stagesWiseOpportunitiesData = filtered;
let stages = this.opportunitiesStateReason;
stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
} else {
this.stagesWiseOpportunitiesData = this.stagesWiseOpportunitiesDataCopy;
let stages = this.opportunitiesStateReason;
stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
}
}
}
Try like this. you have missed to return the for the search function.
NOTE: you have only returned for a function inside search function
function search(searchValue) {
if (searchValue != null && searchValue != "") {
var searchItem = searchValue;
var allOppData = this.stagesWiseOpportunitiesData;
var filtered = _.mapValues(allOppData, statuses =>
_.filter(statuses, statusT =>
_.some(statusT, T => _.includes(T, searchItem))
)
);
this.stagesWiseOpportunitiesData = filtered;
let stages = this.opportunitiesStateReason;
return stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
} else {
this.stagesWiseOpportunitiesData = this.stagesWiseOpportunitiesDataCopy;
let stages = this.opportunitiesStateReason;
return stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
}
}
console.log(search("Test"))

Increment digit part of string in JavaScript

I have a string that contains digit at the end. I want to increase the digit part by 1 when some actions happened.
e.g.
var myString = 'AA11111'
increaseStringValue(myString)
# myString new value => 'AA11112'
also how can I increase chars when string value reached to 'AA99999' so new value of string will be 'AB11111'?
You can split char and digit parts so you can handle them separately.
like:
function increaseStringValue(str){
let charPart = str.substring(0,2);
let digitPart = str.substring(2);
digitPart = +digitPart+1
if(digitPart >= 99999){
digitPart = 11111;
if(charPart[1] == 'Z'){
if(charPart[0] == 'Z'){
throw 'Overflow happened'
}
charPart = String.fromCharCode(charPart.charCodeAt(0)+1) + 'A'
}else{
charPart = charPart[0] + String.fromCharCode(charPart.charCodeAt(1)+1)
}
}
return charPart + digitPart;
}
increaseStringValue('AA11111'); // 'AA11112'
increaseStringValue('AA99999'); // 'AB11111'
increaseStringValue('AZ99999'); // 'BA11111'
increaseStringValue('ZZ99999'); // Exception: Overflow happened
This links will be helpful for you:
ASCII CODES
what is a method that can be used to increment letters?
Edit:
Following function will be suite for unknown length string with dynamic position of char and digit.
function increaseStringValue(str) {
let charOverFlowed = true;
let result = ""
for (let i = str.length - 1; i >= 0; i--) {
let currentChar = str[i];
if ('123456789'.indexOf(currentChar) !== -1) {
if (charOverFlowed) {
currentChar = +currentChar + 1
charOverFlowed = false;
}
if (currentChar > 9) {
currentChar = 1;
charOverFlowed = true;
}
} else if (charOverFlowed) {
currentChar = String.fromCharCode(currentChar.charCodeAt(0) + 1)
charOverFlowed = false;
if (currentChar > 'Z') {
if(i == 0){
throw 'Overflow Happened'
}
currentChar = 'A'
charOverFlowed = true
}
}
result = currentChar + result;
}
return result;
}
increaseStringValue('AAAACA')
// "AAAACB"
increaseStringValue('AAAACA1111')
// "AAAACA1112"
increaseStringValue('A1')
// "A2"
increaseStringValue('Z')
// Uncaught Overflow Happened
increaseStringValue('A1999')
// "A2111"
function increaseStringValue(myString){
return myString.replace(/\d+/ig, function(a){ return a*1+1;});
}
console.log(increaseStringValue("asg61"));
And for next question:
function increaseStringValue(myString){
return myString.replace(/(A)(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?"B11111":"A"+r;
});
}
console.log(increaseStringValue("AA99999"));
And Whole way:
function increaseStringValue(myString){
return myString.replace(/([a-e])(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?String.fromCharCode(a.charCodeAt(0)+1)+"11111":b+r;
});
}
console.log(increaseStringValue("AB99999"));
Please find the snippet useful. If this is what you are expecting.
let stringNum = 'AA11111';//initialise string
let clickTriggered = ()=>{
let startString = "AA";
let newNum = ()=>{
let numberPart = stringNum.split("AA")[1];
let lastChar = stringNum[stringNum.length-1];
return Number(numberPart) != NaN || Number(numberPart) <= 99999 ? Number(numberPart)+1 : 11111;
};
stringNum = `${startString}${newNum()}`
console.log(stringNum)
}
<h1 onclick="clickTriggered()">click here</h1>
You can use String#replace and provide your increment logic in the function callback of the string#replace.
const increaseStringValue = (str) => str.replace(/\d+$/, n => n === '99999' ? 11111 : +n + 1);
console.log(increaseStringValue('AA99999'));
console.log(increaseStringValue('AA11315'));
console.log(increaseStringValue('AA11111'));
I solve this with this solution
let app = new Vue({
el: '#app',
data: {
text: "AA995"
},
methods: {
addOneString: function(str) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz',
length = alphabet.length,
result = str,
i = str.length,
value = str;
while(i >= 0) {
var last = str.charAt(--i),
next = '',
carry = false;
if (isNaN(last)) {
index = alphabet.indexOf(last.toLowerCase());
if (index === -1) {
next = last;
carry = true;
}
else {
var isUpperCase = last === last.toUpperCase();
next = alphabet.charAt((index + 1) % length);
if (isUpperCase) {
next = next.toUpperCase();
}
carry = index + 1 >= length;
if (carry && i === 0) {
var added = isUpperCase ? 'A' : 'a';
result = added + next + result.slice(1);
break;
}
}
}
else {
next = +last + 1;
if(next > 9) {
next = 0;
carry = true;
}
if (carry && i === 0) {
result = '1' + next + result.slice(1);
break;
}
}
result = result.slice(0, i) + next + result.slice(i + 1);
if (!carry) {
break;
}
}
console.log("result",result);
if (value !== result ) this.text = result;
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div class="container" id="app">
<button #click="addOneString(text)">Add one</button>
</br>
<p> {{text}} </p>
</div>

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;
}

Would like to create an array with number of matches for specific regexs

Would like to create an array with number of matches for specific regexs:
So if january was found 5 times , feb 3 the table would be:
monthFound=[5,3......]
function findMonth(){
var fpath='log.txt';
var monthFound=[]
fs.readFileSync(fpath).toString().split('\n').forEach(function(line)
{
var regExpressions1=[/-jan-/,/-feb-/,/-mar-/,/-apr-/,/-may-/,/-jun-/,/-jul-/,/-aug/,/-sep-/,/-oct-/,/-nov/,/-dec-/];
for (var i = 0; i<regExpressions1.length;i++)
{
var idx = line.match(regExpressions1[i]);
if (idx !== null) {
y++;
}
}
});
}
This will return an array with each month match count:
fs.readFileSync(fpath).toString().split('\n').reduce((count, str) => {
['-jan-','-feb-','-mar-','-apr-','-may-','-jun-','-jul-','-aug-','-sep-','-oct-','-nov-','-dec-'].forEach((month, idx) => {
const match = (str.match(new RegExp(month, 'g')) || []).length;
if (count[idx]) {
count[idx] += match;
} else {
count[idx] = match;
}
});
return count;
}, []);
Use this :
function findMonth(){
var fpath='log.txt';
var monthFound=[]
fs.readFileSync(fpath).toString().split('\n').forEach(function(line) {
var regExpressions1=["-jan-","-feb-","-mar-","-apr-","-may-","-jun-","-jul-","-aug-","-sep-","-oct-","-nov-","-dec-"];
for (var i = 0; i<regExpressions1.length;i++) {
var idx = line.match(new RegExp(Expressions1[i]));
monthFound[i] === idx.length
}
});
}

Non-repeating stack in JavaScript

I need to keep a stack of 10 items (value primitives, not objects) where no item is repeated. Here's my initial stab at an implementation. Any suggestions for improvements?
var items = [];
function newItem() {
return Math.floor(Math.random() * 50);
}
function inArray(arr, val) {
var in_arr, i;
in_arr = false;
i = arr.length;
if (i < 1) {
return in_arr;
}
do {
if (arr[i - 1] === val) {
in_arr = true;
break;
}
} while (--i);
return in_arr;
}
function addItem() {
var new_item;
while (items.length > 9) {
items.shift();
}
do {
new_item = newItem();
} while (inArray(items, new_item));
items.push(new_item);
}
while (items.length > 9) {
items.shift();
}
can be written without iteration as
var len = items.length;
if (len > 9) {
items = items.slice(len - 9);
}
Since JS 1.6, inArray can be written as array.indexOf(element) != -1. Otherwise,
if (i < 1) {
return in_arr;
}
do {
if (arr[i - 1] === val) {
in_arr = true;
break;
}
} while (--i);
return in_arr;
can be written more simply as
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
function inArray(arr, val) {
return !!~arr.indexOf(val);
}
with this shim if needed
function addItem(item) {
if (inArray(items, item)) return false;
if (items.length > 9) items = items.slice(len - 9);
items.push(item);
return true;
}
I would rewrite the hold thing like this:
function stack10() {
var items = arguments || [];
this.addItem = function (item) {
var len = items.length;
if (!!~items.indexOf(item)) return;
if (len > 9) items = items.slice(len - 9);
items.push(item);
}
this.peek = function() {
if (items.length === 0) return null;
return items[items.length-1];
}
this.pop = function () {
return items.pop();
}
}
var myStack = new stack10();
myStack.addItem(10);
myStack.peek(); // 10
myStack.pop(); // 10
myStack.pop(); // undefined
// default values
var myStack2 = new stack10(1,2,3,4);
myStack2.addItem(10);
myStack2.peek(); // 10
myStack2.pop(); // 10
myStack2.pop(); // 4
Why not use a heap? You can do O(lg n) insert and removal instead of O(n), and it's still in-place.

Categories