Why is my decryption function not working? - javascript

I created a function to encrypt and decrypt messages. the encrypting works fine. but when I try to log encrypted Hello World! it just logs H.
const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!##$%^&*()_+-=[]{}|;':,./<>?\" ".split("");
function encrypt(message) {
message = message.split("")
var output = []
message.forEach(element => {
if (chars.includes(element)) {
output.push("c" + chars.indexOf(element))
} else if (numbs.includes(element)) {
output.push("n" + numbs.indexOf(element))
} else if (symbols.includes(element)) {
output.push("s" + symbols.indexOf(element))
} else {
console.log(element)
throw new Error(`Unknown character`)
}
});
return output.join("")
}
function decrypt(message) {
message = message.split("");
var output = [];
var prevDeter;
var prevNumbs = [];
message.forEach(element => {
if (element == "c") {
prevDeter = "c"
if (prevNumbs.length > 0) {
output.push(chars[parseInt(prevNumbs.join(""))])
}
} else if (element == "n") {
prevDeter = "n"
if (prevNumbs.length > 0) {
output.push(numbs[parseInt(prevNumbs.join(""))])
}
} else if (element == "s") {
prevDeter = "s"
if (prevNumbs.length > 0) {
output.push(symbols[parseInt(prevNumbs.join(""))])
}
} else {
prevNumbs.push(element)
}
});
return output.join("")
}
//expected to log Hello World! but logs H and when starting the message with a symbol or number it just logs nothing
console.log(decrypt(encrypt("Hello World!")))
Fixed it, i edited the encoding system to place a - between chars and the decoding system to just split the message at - and check if the element starts with c n or s. and then i just used substring to get the number and decrypt it
const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!##$%^&*()_+-=[]{}|;':,./<>?\" ".split("");
function encrypt(message) {
message = message.split("");
var output = [];
message.forEach(element => {
if(chars.includes(element)) {
output.push("-c" + chars.indexOf(element));
}else if(numbs.includes(element)) {
output.push("-n" + numbs.indexOf(element));
}else if(symbols.includes(element)) {
output.push("-s" + symbols.indexOf(element));
}else{
console.log(element);
throw new Error(`Unknown character`);
};
});
return output.join("");
};
function decrypt(message) {
message = message.split("-");
console.log(message)
var output = [];
message.forEach(element => {
if(element.startsWith("c")) {
output.push(chars[element.substring(1)]);
}else if(element.startsWith("n")) {
output.push(numbs[element.substring(1)]);
}else if(element.startsWith("s")) {
output.push(symbols[element.substring(1)]);
}else if(element.length < 1){
}else{
throw new Error(`Invalid message`);
}
});
return output.join("");
};
console.log(decrypt(encrypt("Hello World!")));

You need to split the encoded string based on set/index pairs. This is easy enough to do with a look-ahead regular expression and splitting before a c, n or an s. /(?=[cns])/
const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!##$%^&*()_+-=[]{}|;':,./<>?\" ".split("");
function encrypt(message) {
message = message.split("")
var output = []
message.forEach(element => {
if (chars.includes(element)) {
output.push("c" + chars.indexOf(element))
} else if (numbs.includes(element)) {
output.push("n" + numbs.indexOf(element))
} else if (symbols.includes(element)) {
output.push("s" + symbols.indexOf(element))
} else {
console.log(element)
throw new Error(`Unknown character`)
}
});
return output.join("")
}
function decrypt(message) {
message = message.split(/(?=[cns])/);
var output = [];
message.forEach(element => {
let set;
switch(element[0]){
case 'c':
set = chars;
break;
case 'n':
set = numbs;
break;
case 's':
set = symbols;
break;
}
const index = parseInt(element.substring(1));
output.push(set[index]);
});
return output.join('');
}
const encrypted = encrypt("Hello World!");
console.log(encrypted);
//expected to log Hello World! but logs H and when starting the message with a symbol or number it just logs nothing
console.log(decrypt(encrypted));

Related

How to optimize memory in an algorithm

How can I optimize this
if the string can be split without a 4, 422 and 2222 without a remainder, returns true
tests:
input "4" output "true"(4)
input "44" output "true" (4 4)
input "42" output false(4 2!==2222 || 422 || 4)
input "4224224" output true (422 422 4)
input "42222" output true (4 2222)
input "22224"output true (2222 4)
let solution = (password) => {
if (!password) return false
while (password) {
if (password.includes('2222')) {
while (password.includes('2222')) {
password = password.replace('2222', '')
}
}
if (password.includes('422')) {
while (password.includes('422')) {
password = password.replace('422', '')
}
}
if (password.includes('4')) {
while (password.includes('4')) {
password = password.replace('4', '')
}
}
return !!!password
}
}
console.log(solution('4'));
console.log(solution('44'));
console.log(solution('42'));
console.log(solution('4224224'));
console.log(solution('42222'));
console.log(solution('22224'));
this is the same:
let solution = (password) => {
const searchValue = ['2222', '422', '4']
if (!password) return false
for (let elem = 0, i = searchValue[0]; password; elem++) {
if (password.includes(i)) {
while (password.includes(i)) {
password = password.replace(i, '')
}
}
i = searchValue[elem]
if (elem === 3) {
return !!!password
}
}
return !!!password
}
console.log(solution('4'));
console.log(solution('44'));
console.log(solution('42'));
console.log(solution('4224224'));
console.log(solution('42222'));
console.log(solution('22224'));
Memory limitation on startup - 100 MB
must work with -> const bigStr = new Array(9999999).fill(() =>["4", "422", "2222" ][Math.floor(Math.random() * 3)]).map(f => f()).join('')
Sorry, I forgot to mention that regular expressions are not allowed use
1) You can get the desired result with recursion
const matches = ["4", "2222", "422"];
function isMatch(str) {
if (str.trim() === "") return true;
for (let i = 0; i < matches.length; ++i) {
if (str.startsWith(matches[i])) {
if (isMatch(str.replace(matches[i], ""))) return true;
}
}
return false;
}
console.log(isMatch("4"));
console.log(isMatch("44"));
console.log(isMatch("42"));
console.log(isMatch("4224224"));
console.log(isMatch("42222 "));
console.log(isMatch("2222"));
2) You can use regex here \b(4|2222|422)+\b
const regex = /\b(4|2222|422)+\b/;
function isMatch(str) {
return regex.test(str);
}
console.log(isMatch("4"));
console.log(isMatch("44"));
console.log(isMatch("42"));
console.log(isMatch("4224224"));
console.log(isMatch("42222 "));
console.log(isMatch("2222"));
You can just use replaceAll instead of replacing the string each time and check if it is in there another time:
const bigStr = new Array(9999999).fill(() => ["4", "422", "2222"][Math.floor(Math.random() * 3)]).map(f => f()).join('');
const solution = (password) => {
return password !== "" && !password.replaceAll('2222', '').replaceAll('422', '').replaceAll('4', '');
}
console.log(solution("4"));
console.log(solution("44"));
console.log(solution("42"));
console.log(solution("4224224"));
console.log(solution("42222"));
console.log(solution("2222"));
console.log(solution(bigStr))

String.prototype.substring giving wrong output when I pass in a variable

I'm working on the coding exercise to build a text editor and add some operations like append, delete and move cursor. Can anyone please explain me why in the delete function, text.substring(cursorPosition + 1) gives me an empty string instead of 'ou!' like when I do text.substring(6).
function textEditor2_2(queries) {
// create cursurPosition, text and result text array variables
let cursorPosition = 0;
let text = "";
let textArray = [];
// append text function
const appendText = (string) => {
text += string;
cursorPosition += string.length;
textArray.push(text);
}
// move cursur position function
const moveCursor = (specifiedPosition) => {
if (specifiedPosition < 0) {
cursorPosition = 0;
} else if (specifiedPosition > cursorPosition) {
return;
} else {
cursorPosition = specifiedPosition
}
}
// delete text function
const deleteText = () => {
console.log(text) // 'Hey, you!'
console.log(cursorPosition) // '5'
console.log(text.substring(6)) // 'ou!'
console.log(text.substring(cursorPosition + 1)) // ''
text = string.substring(0, cursorPosition) + string.substring(cursorPosition + 1);
textArray.push(text);
}
// iterate thru queries and apply callback based on operation type
queries.forEach(operation => {
if (operation[0] === 'APPEND') {
appendText(operation[1])
} else if (operation[0] === 'MOVE') {
moveCursor(operation[1])
} else if (operation[0] === 'DELETE') {
deleteText()
}
})
return textArray;
}
let queriesSample = [
["APPEND", "Hey, you!"],
["MOVE", "5"],
["DELETE"],
]
console.log(textEditor2_2(queriesSample));

How to make a fully functional brainf*ck interpreter?

I have tried to implement a BF interpreter in Javascript. It works for many programs like printing Hello world, looping, etc.
Here is link to a sample interpreter that I use for comparing outputs: https://sange.fi/esoteric/brainfuck/impl/interp/i.html
But when I try to run a BF to C program, it gets stuck like it is in an infinite loop. It however does work in the sample interpreter above. What am I doing wrong?
Here is a BF code that converts an input BF code to C.
+++[>+++++<-]>>+<[>>++++>++>+++++>+++++>+>>+<++[++<]>---]
>++++.>>>.+++++.>------.<--.+++++++++.>+.+.<<<<---.[>]<<.<<<.-------.>++++.
<+++++.+.>-----.>+.<++++.>>++.>-----.
<<<-----.+++++.-------.<--.<<<.>>>.<<+.>------.-..--.+++.-----<++.<--[>+<-]
>>>>>--.--.<++++.>>-.<<<.>>>--.>.
<<<<-----.>----.++++++++.----<+.+++++++++>>--.+.++<<<<.[>]<.>>
,[>>+++[<+++++++>-]<[<[-[-<]]>>[>]<-]<[<+++++>-[<+++>-[<-->-[<+++>-
[<++++[>[->>]<[>>]<<-]>[<+++>-[<--->-[<++++>-[<+++[>[-[-[-[->>]]]]<[>>]<<-]
>[<+>-[<->-[<++>-[<[-]>-]]]]]]]]]]]]]
<[
-[-[>+<-]>]
<[<<<<.>+++.+.+++.-------.>---.++.<.>-.++<<<<.[>]>>>>>>>>>]
<[[<]>++.--[>]>>>>>>>>]
<[<<++..-->>>>>>]
<[<<..>>>>>]
<[<<..-.+>>>>]
<[<<++..---.+>>>]
<[<<<.>>.>>>>>]
<[<<<<-----.+++++>.----.+++.+>---.<<<-.[>]>]
<[<<<<.-----.>++++.<++.+++>----.>---.<<<.-[>]]
<[<<<<<----.>>.<<.+++++.>>>+.++>.>>]
<.>
]>
,]
<<<<<.<+.>++++.<----.>>---.<<<-.>>>+.>.>.[<]>++.[>]<.
Here is my implementation:
class Node {
constructor() {
this.value = 0;
this.next = null;
this.prev = null;
}
increment() {
this.value++;
}
decrement() {
this.value--;
}
}
class Memory {
constructor() {
this.current = new Node();
this.outputBuffer = [];
}
moveRight() {
if (this.current.next === null) {
const rightNode = new Node();
rightNode.prev = this.current
this.current.next = rightNode;
}
this.current = this.current.next;
}
moveLeft() {
if (this.current.prev === null) {
const leftNode = new Node()
leftNode.next = this.current;
this.current.prev = leftNode;
}
this.current = this.current.prev;
}
increment() {
this.current.increment();
}
decrement() {
this.current.decrement();
}
print() {
this.outputBuffer.push(String.fromCharCode(this.current.value));
}
input(ch) {
this.current.value = ch.charCodeAt(0);
}
}
class Interpreter {
reset() {
this.memory = new Memory();
this.instructionPointer = 0;
this.inputPointer = 0;
this.openingToClosingBrackets = new Map();
this.closingToOpeningBrackets = new Map();
}
interpret(code, input = "") {
this.reset();
this.code = code;
this.matchSquareBrackets();
this.input = input;
while (!this.reachedEOF()) {
const instruction = this.code[this.instructionPointer];
switch (instruction) {
case "+": this.memory.increment(); break;
case "-": this.memory.decrement(); break;
case ">": this.memory.moveRight(); break;
case "<": this.memory.moveLeft(); break;
case ".": this.memory.print(); break;
case ",": this.memory.input(this.getNextCharacter()); break;
case "[": this.loopStart(); break;
case "]": this.loopEnd(); break;
}
this.instructionPointer++;
}
return this.memory.outputBuffer.join("");
}
reachedEOF() {
return this.instructionPointer >= this.code.length;
}
getNextCharacter() {
if (this.inputPointer >= this.input.length) {
throw new Error("EOF. Expected more input characters.");
}
return this.input[this.inputPointer];
}
loopStart() {
if (this.memory.current.value !== 0) {
return;
}
this.instructionPointer = this.openingToClosingBrackets.get(
this.instructionPointer
);
}
loopEnd() {
if (this.memory.current.value === 0) {
return;
}
this.instructionPointer = this.closingToOpeningBrackets.get(
this.instructionPointer
);
}
matchSquareBrackets() {
const openingStack = [];
for (let i = 0; i < this.code.length; i++) {
const ch = this.code[i];
if (ch === "[") {
openingStack.push(i);
}
if (ch === "]") {
if (openingStack.length === 0) {
throw new Error("No matching '[' for ']' at index: " + i);
}
const openingMatch = openingStack.pop();
this.openingToClosingBrackets.set(openingMatch, i);
this.closingToOpeningBrackets.set(i, openingMatch);
}
}
if (openingStack.length > 0) {
throw new Error(
"No matching ']' for '[' at indices: " + openingStack.join(", ")
);
}
}
}
Your getNextCharacter doesn't work correctly: if there's at least one character of input, it will return that character each time it's called - it never increments the input index. Since the bf2c program keeps reading input until there is no more input, this causes your infinite loop.
Another problem with your code is that you throw an exception when , is used and there is no more input, causing the bf2c to abort with an exception when it reaches the end of the input. So you'll either need to explicitly terminate the input with a \0, so that the bf2c program knows when to stop reading or change getNextCharacter to return '\0' at the end of input instead of throwing an exception.

find cities and country name from string

I have cities and countires list in a json file. For a given string, I need to check the city name and country name is present or not. If present I have to capitalize the word. what is the best way to acheive this in node JS
Please consider json from this link.
https://raw.githubusercontent.com/russ666/all-countries-and-cities-json/master/countries.json
my input is "united states to play davis cup in bratislava"
output should be "United States to play davis cup in Bratislava"
Hint: First letter of city and country name should be capital.
I am expecting code something like this
var myString="united states to play davis cup in bratislava";
var data=myjson;
var i=0;
myString=myString.split("");
for(i=0;i<myString.length;i++){
var output="";
//help this line
var check=myString[i].match(data)
if(check){
output+=myString[i].charAt(0).toUpperCase() + myString[i].slice(1);
}
else{
output+=myString[i]}
}
It all starts from function start() at the bottom. For displaying purpose i've used a small dataset but you can require the data from the json file by using const data = require('data.json'). I've tested for large dataset also, works like a charm. Hope it helps.
const data = {
"United States":[
"Washington","Bratislava","Hard","Going"],
"Afghanistan": [
"Herat",
"Kabul",
"Kandahar",
"Molah",
"Rana",
"Shar",
"Sharif",
"Wazir Akbar Khan"
]};
Array.prototype.myJoin = function(start,end){
if(!start) start = 0;
if(!end) end = this.length - 1;
end++;
return this.slice(start,end);
};
const getCityData = async (country) => {
return country;
}
const changeFormat = async () => {
try {
let countries = Object.keys(data).map( (country, index) => {
return country;
})
let citiesData = [];
await countries.map( (country, index) => {
citiesData = citiesData.concat(data[country]);
})
return countries.concat(citiesData);
} catch (err) {
return err;
}
}
const checkSentence = (text, text_original, number, modified_data) => {
return new Promise((resolve, reject)=>{
try {
if( !text || !text.length ){
throw new Error('empty text');
}
// console.log('started ' + number);
// console.log('number ' + number +' started')
let upperCase = [];
const number_const = number;
let temp1 = new Array(text.length);
temp1.fill(2);
temp1.map( (v, i) => {
// let temp = text;
let temp = [...text_original, ...[]];
// console.log('i' + i);
// console.log('number' + number);
if(i + number <= text.length ) {
// console.log('inside 1st if');
temp = temp.slice(i, i + number)
// console.log(text + ' 1');
temp = temp.join(' ')
// console.log(text + ' 2');
temp = temp.toLowerCase();
// console.log(text + ' 3');
if(modified_data.indexOf(temp) != -1){
upperCase.push({ start: i, end: i + number - 1 })
}
}
})
let toBeChanged = [];
if(upperCase.length){
upperCase.map( (v, i) => {
// console.log(v);
let arr = range( v.start, v.end )
toBeChanged = toBeChanged.concat(arr);
})
}
// console.log('ended number' + number);
// console.log(toBeChanged);
return resolve(toBeChanged);
} catch (err) {
return reject(err);
// console.error(err);
// return false;
}
})
}
const range = (start, end) => {
// console.log(start);
// console.log(end);
return Array(end - start + 1).fill().map((_, idx) => start + idx)
}
const start = async() => {
try {
excludeWords.map( (word, index) => {
excludeWords[index] = excludeWords[index].toLowerCase();
});
let modified_data_1 = await changeFormat();
let maximum = 1;
modified_data = modified_data_1.map( (v, i) => {
if(v.split(' ').length > maximum){
maximum = v.split(' ').length
}
if(excludeWords.indexOf(v.toLowerCase()) == -1) {
return v.toLowerCase();
}
});
text = text.split(' ');
if(maximum > text.length){
maximum = text.length;
}
// console.log(maximum);
let temp = new Array(maximum);
temp.fill(2);
let answer = await temp.map( (v, i) => {
let tempArray = [...text, ...[]];
let tempArray1 = [...text, ...[]];
return checkSentence(tempArray, tempArray1, (maximum - i), modified_data);
})
return Promise.all(answer).then( (results) => {
let merged = [].concat.apply([], results);
// console.log('merged');
merged = new Set(merged);
merged = [...merged];
// console.log(merged);
merged.map((v, i) => {
if(v == undefined || v == null){
return;
}
let temp1 = text[v].split('');
temp1[0] = temp1[0].toUpperCase();
text[v] = temp1.join('');
})
// console.log(text.join(' '));
return text.join(' ');
}).catch((err)=>{
console.log(err);
})
} catch (err) {
// console.error('here ERROR');
console.error(err);
return false;
}
}
let excludeWords = ['Hard', 'Going'];
let text = 'united states to davis cup hard wazir Akbar Khan in bratislava';
( async () => {
let answer = await start();
console.log(answer);
})();
Hi I have done in simple way it is also working. My problem is in the string the word "davis" also present as a city in json. How to not capitalize that word. For ex: "Hard", "Going" these words also have city name. but these words not be considered as city in my program.
Case 1:
Input: taiwan hit hard by sars outbreak.
Output should be: Taiwan hit hard by sars outbreak.
My output: Taiwan hit Hard by sars outbreak.
Please install capitalize npm and use data.json folder in your root folder to execute below code
var myData=require("./data");
var countriesArray=Object.keys(myData.data);
var citiesArray=Object.values(myData.data);
var capitalize=require('capitalize');
var citiesFlatten = [].concat.apply([], citiesArray);
var countryCities=countriesArray.concat(citiesFlatten);
var str = 'russia ponders space tourism deal';
var pattern = new RegExp("\\b("+countryCities.join("|")+")\\b","ig");
var matchArray=str.match(pattern);
if(!!matchArray){
matchArray.forEach(function(item) {
str=str.replace(item,capitalize.words(item));
});
console.log( str.replace(/^\w/, c => c.toUpperCase()));
}

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>

Categories