I want to generate unique alphabetical keys in alphabetical order |angularJs - javascript

I want to generate keys in alphabetical order in such a way that it begins with
aaaaa
then the next would be aaaab and after reaching to aaaaz the string should be aaaba and then aaabb and so on , so that the keys generate properly
My sample JSON to be created
var keygen={aaaaa,
aaaab,
aaaac .........aaaaz,aaaba ....}
my javascript
$scope.doKeyGen=function(lastValueInJSON)
{ // Do something
}

This will work for you. JS Fiddle is here.
https://jsfiddle.net/3d789okv/7/
Make sure that you the last value you give will be hit.
Otherwise you are going to an infinite loop hell.
Also you can configure the number of letters in the call to getNext().
But make sure that you set the equal number of letters in the first value and "aaaaa" and the last value "asxas"
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
var json = [];
function getNext(charCount,lastValue){
changeIndex = charCount -1;
var newValue = "";
while (changeIndex >= 0){
if(lastValue[changeIndex] !== "z"){
var changed = lastValue[changeIndex];
var replacechanged = String.fromCharCode(changed.charCodeAt(0)+1);
newValue = lastValue.replaceAt(changeIndex,replacechanged)
for(var j=changeIndex+1; j < charCount; ++j){
newValue = newValue.replaceAt(j,"a");
}
return newValue;
}
changeIndex--;
}
}
function createJSON(lastValue){
if(!json.length){
//var startPrefix = "aaaaa";
json.push("aaaaa");
while(lastValue !== json[json.length-1]){
json.push(getNext(5,json[json.length-1]));
}
console.log(json);
}
}
createJSON("aaabz");

You need to use recursive function to generate your keys.
I've written some piece of code in this fiddle link, which generate keys as per your requirement and create JSON too.
Please note I assume small case alphabets keys only. and used 3 length string (aaa), You can use 4 length also but performance degrades.
You can change any first key in input in attached fiddle, like 'aay' then code generate next all possible keys.(aaz, aba,.....,zzz).

You can use this
function getNextKey(lastKeyCode, changeIndex)
{
var charCodes = [];
if( changeIndex == undefined )
changeIndex = lastKeyCode.length - 1;
if(changeIndex - 1 > -1 && lastKeyCode.charCodeAt(changeIndex) == 122 )
{
lastKeyCode = getNextKey(lastKeyCode, changeIndex - 1);
}
lastKeyCode.split('').forEach(function(e){charCodes.push(e.charCodeAt())});
charCodes[changeIndex] = 97 + (charCodes[changeIndex] - 96 ) % 26;
return String.fromCharCode.apply(0, charCodes);
}
//-------------------EDIT ( GENERATE KEYS LIKE THIS )------------
function generateKeys(lastKey)
{
var json = [];
var nextKey = new Array(lastKey.length + 1 ).join('a');
json.push(nextKey);
while( nextKey != lastKey )
{
json.push( (nextKey = getNextKey(nextKey)) )
}
return json;
}
//---------------------------Example----------------------------
var last = 'test';
console.log('Last Key : '+last+' | Generated key length : '+generateKeys(last).length);

Related

Any alternative way of using this .length & .split()?

I want to split lower, upper & also the value of textBox without using .split() and also I want
to find the length of the string without using .length. Can anybody solve my problem I am tried but
I cannot find the exact logic for this problem.
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
function toUpper(input) {
var upperCase = uppercase.split(""); //other way to split uppercase
var lowerCase = lowercase.split(""); //other way to split lowercase
var inputText = input.split(""); //other way to split input
var newText = "";
var found;
for (var i = 0; i < inputText.length; i++) { //not using .length to other way to find the size of inputText
found = false;
for (var ctr = 0; ctr < lowerCase.length; ctr++) { //not using .length other way to find the size of lowerCase
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
You can count the length of a string using the array function reduce.
Reduce loops over all elements in an array and executes a function you give it to reduce it to one value, you can read more here.
To get reduce working on strings, you need to use Array.from, like this:
Array.from(lowerCase).reduce((sum, carry) => sum + 1, 0) // 26
Reduce accepts a starting argument, which we set to zero here.
This way you do not need to use the split or length functions.
You don't need to check if the input is in a string either, you can use charCodeAt() and fromCharCode().
If you take your input and loop through it using Array.from() then forEach, you can get something which looks like this:
function print() {
const input = document.querySelector('#input').value;
document.querySelector('#target').value = stringToUpper(input);
}
function stringToUpper(input) {
let output = "";
Array.from(input).forEach(char => output += charToUpper(char));
return output;
}
function charToUpper(char) {
let code = char.charCodeAt(0);
code >= 97 && code <= 122 ? code -= 32 : code;
return String.fromCharCode(code);
}
<div>
<input id="input" placeholder="enter text here">
</div>
<button onclick="print()">To Upper</button>
<div>
<input id="target">
</div>
The key line is where we take the output and add the char (as upper) to it:
output += charToUpper(char)
If you don't know about arrow functions, you can read more here
This line:
code >= 97 && code <= 122 ? code -= 32 : code;
is just checking if the char is lower case (number between 97 and 122) and if so, subtracting 32 to get it to upper case.
The reason it is subtract not add is in utf-16, the chars are laid out like this:
ABCDEFGHIJKLMNOPQRTUWXYZabcdefghijklmnopqrtuwxyz
See here for more
I don't know what you mean by "split the value of textBox", but one way to determine the length of a string without using .length would be to use a for...of loop and have a counter increment each time it runs to keep track of the number of characters in the string.
let string = 'boo'
let lengthCounter = 0
for (let char of string) {
lengthCounter++
}
//lengthCounter = 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
You can define your own split and length functions:
function mySplit(a){
var counter = 0;
rslt = [];
var val = a[counter];
while(typeof val != "undefined"){
rslt.push(a[counter]);
counter ++;
val = a[counter];
}
return rslt;
}
function myLength(a){
var counter = 0;
var val = a[counter];
while(typeof val != "undefined"){
counter ++;
val = a[counter];
}
return counter;
}
Your function now should be like:
function toUpper(input) {
var upperCase = mySplit(uppercase);
var lowerCase = mySplit(lowercase);
var inputText = mySplit(input);
var newText = "";
var found;
for (var i = 0; i < myLength(inputText); i++) {
found = false;
for (var ctr = 0; ctr < myLength(lowerCase); ctr++) {
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
The simplest way would be to just use the build in function of javascript .toUpperCase() (see example 1). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
Else if you insist on using a for.loop you may do so aswell (see example two). You do not need the split() function since a string already is an arrayof characters. Also be aware that not all characters in the web have lowercase counterparts, so the logic itself is flawed.
//REM: This lines are not required.
/*
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
*/
//REM: Version 1 (using string.toUpperCase())
(function toUpper1(input){
var tReturn = (input || '').toUpperCase();
console.log('toUpper1', tReturn);
return tReturn
}('abcDEFghiJKL'));
//REM: Version 2 (using your way)
(function toUpper2(input){
var tReturn = '';
if(input && input.length){
for(let i=0, j=input.length; i<j; i++){
tReturn += (input[i] === input[i].toLowerCase()) ? input[i].toUpperCase() : input[i]
}
};
console.log('toUpper2', tReturn);
return tReturn
}('abcDEFghiJKL'));

JavaScript Dynamically created object undefined

I am doing the freecodecamp algorithmic challenge "Caesars Cipher". I have a problem with my code. I try to generate a lookup table as a dynamic object and for some reason it doesn't register. When doing console.log it is says "lookup table is undefined". It is the same with the Acode variable. If I comment out the console.logs then it will work but it will not encrypt anything because of the below part which checks if the char from strArr exists in the lookupTable, if not, it should assign the same value to the encryptedArr (this was done to not encrypt commas, spaces etc):
strArr.forEach(function(thisArg) {
var newValue;
if(lookupTable[thisArg] !== undefined ) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
Ofcourse lookupTable[thisArg] is always undefined.
Here is the whole function with the above part as well:
function rot13(str) { // LBH QVQ VG!
var strArr;
var encryptedArr = [];
var Acode;
var lookupTable = {}; //this object will contain the mapping of letters
var encryptedString;
//check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic
Acode = 'A'.charCodeAt(0);
console.log(Acode);
//generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time)
//this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works
for (i = 0; i < 26; i++) {
lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((Acode + i) - 13) % 26);
console.log(lookupTable[String.fromCharCode(Acode + i)]);
}
//save the string into the array
strArr = str.split("");
//change letters into numbers and save into the code array
strArr.forEach(function(thisArg) {
var newValue;
if (lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
encryptedString = encryptedArr.join("");
return encryptedString;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
console.log(Acode);
What am I doing wrong with the lookupTable object creation AND with the below?
Acode = 'A'.charCodeAt(0);
There's no undefined variable. The problem with your code is in how you calculate the lookup table entries. Your code is mapping every character to itself, not shifting by 13. The correct formula is
Acode + ((i + 13) % 26)
Acode is the ASCII code for the letter, and you shouldn't be including that when performing the modular shift. You just want to apply the modulus to the offset from the beginning of the alphabet after shifting it by 13.
function rot13(str) { // LBH QVQ VG!
var strArr;
var encryptedArr = [];
var Acode;
var lookupTable = {}; //this object will contain the mapping of letters
var encryptedString;
//check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic
Acode = 'A'.charCodeAt(0);
// console.log(Acode);
//generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time)
//this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works
for (i = 0; i < 26; i++) {
lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((i + 13) % 26));
// console.log(lookupTable[String.fromCharCode(Acode + i)]);
}
//save the string into the array
strArr = str.split("");
//change letters into numbers and save into the code array
strArr.forEach(function(thisArg) {
var newValue;
if (lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
encryptedString = encryptedArr.join("");
return encryptedString;
}
// Change the inputs below to test
var result = rot13("SERR PBQR PNZC");
console.log(result);

I need to get the last two value after dot using javascript split

I am getting the results like demo.in,demo.co.in,demo.tv,demo.org.in
I need to split the extension separately using JavaScript split function
var vsp = i.split(".");
this is my code I will get the result as
demo,in demo,co,in
but I need to get the extension separately
Working fiddle(demo version)
var values = [
"demo.in",
"demo.co.in",
"demo.tv","demo.org"
];
var results = [];
// iterate through the values
for (var i = 0, len = values.length; i < len; i++) {
// Split the parts on every dot.
var parts = values[i].split(".");
// Remove the first part (before the first dot).
parts = parts.slice(1, parts.length);
// Join the results together
results.push(parts.join("."));
};
console.dir(results); // all done
// Nicely display the values for the OP:
for (var i = 0, len = results.length; i < len; i++) {
document.body.innerHTML += (i + 1) + ": " + results[i] + "<br />";
};
I have no idea what you want, so here's some functions to cover the likely cases:
var s = 'demo.co.in'
// Return everything before the first '.'
function getExtension(s) {
var m = s.match(/^[^.]+/);
return m? m[0] : '';
}
alert(getExtension(s)); // demo
// Return everything after the last '.'
function getExtension2(s) {
var m = s.match(/[^.]+$/);
return m? m[0] : '';
}
alert(getExtension2(s)); // in
// Return everything after the first '.'
function getExtension3(s) {
return s.replace(/^[^.]+\./, '');
}
alert(getExtension3(s)); // co.in
I could not understand exactly .. "the extension" . You can try like below code
var urls = "demo,demo.in,my.demo.co.in,demo.tv,demo.org.in"
.split(',');
var splited = urls.reduce( function( o, n ){
var parts = n.split( '.' );
o[ n ] = (function(){
var ext = [];
while( !(parts.length == 1 || ext.length == 2) ) {
ext.unshift( parts.pop() );
};
return ext.join('.');
}());
return o;
}, {} );
console.log( JSON.stringify( splited ) );
which prints
{
"demo":"",
"demo.in":"in",
"my.demo.co.in":"co.in",
"demo.tv":"tv",
"demo.org.in":"org.in"
}
process result using
for( var i in splited ) {
console.log( i, splited[i]);
}
Try this:
var vsp = i.split(".");
for(var i=0; i< vsp.length; i++){
if(i !== 0){ //leaving the first match
// do something with vsp[i]
}
}
I hope you are not considering www also. :). If so, then keep i>1 instead of i !== 0.
There are several ways to do it (probably none as easy as it should be). You could define a function like this:
function mySplit(str, delim) {
var idx = (str.indexOf(delim) == -1) ? str.indexOf(delim) : str.length;
return [str.substr(0,idx), str.substr(idx)];
}
And then call it like: var sp = mySplit(i, ".");
You can also use lastIndexOf, which returns the location of the last . and from there you can get the rest of the string using substring.
function getExtension(hostName) {
var extension = null;
if(hostName && hostName.length > 0 && hostName.indexOf(".") !== -1) {
extension = hostName.substring(hostName.lastIndexOf(".") + 1);
}
return extension;
}
From there, you can use this function in a loop to get the extensions of many host names.
Edit Just noticed the "last two values" part in the title :) Thanks #rab

remove value from comma separated values string

I have a csv string like this "1,2,3" and want to be able to remove a desired value from it.
For example if I want to remove the value: 2, the output string should be the following:
"1,3"
I'm using the following code but seems to be ineffective.
var values = selectedvalues.split(",");
if (values.length > 0) {
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
index = i;
break;
}
}
if (index != -1) {
selectedvalues = selectedvalues.substring(0, index + 1) + selectedvalues.substring(index + 3);
}
}
else {
selectedvalues = "";
}
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
If the value you're looking for is found, it's removed, and a new comma delimited list returned. If it is not found, the old list is returned.
Thanks to Grant Wagner for pointing out my code mistake and enhancement!
John Resign (jQuery, Mozilla) has a neat article about JavaScript Array Remove which you might find useful.
function removeValue(list, value) {
return list.replace(new RegExp(",?" + value + ",?"), function(match) {
var first_comma = match.charAt(0) === ',',
second_comma;
if (first_comma &&
(second_comma = match.charAt(match.length - 1) === ',')) {
return ',';
}
return '';
});
};
alert(removeValue('1,2,3', '1')); // 2,3
alert(removeValue('1,2,3', '2')); // 1,3
alert(removeValue('1,2,3', '3')); // 1,2
values is now an array. So instead of doing the traversing yourself.
Do:
var index = values.indexOf(value);
if(index >= 0) {
values.splice(index, 1);
}
removing a single object from a given index.
hope this helps
Here are 2 possible solutions:
function removeValue(list, value) {
return list.replace(new RegExp(value + ',?'), '')
}
function removeValue(list, value) {
list = list.split(',');
list.splice(list.indexOf(value), 1);
return list.join(',');
}
removeValue('1,2,3', '2'); // "1,3"
Note that this will only remove first occurrence of a value.
Also note that Array.prototype.indexOf is not part of ECMAScript ed. 3 (it was introduced in JavaScript 1.6 - implemented in all modern implementations except JScript one - and is now codified in ES5).
// Note that if the source is not a proper CSV string, the function will return a blank string ("").
function removeCsvVal(var source, var toRemove) //source is a string of comma-seperated values,
{ //toRemove is the CSV to remove all instances of
var sourceArr = source.split(","); //Split the CSV's by commas
var toReturn = ""; //Declare the new string we're going to create
for (var i = 0; i < sourceArr.length; i++) //Check all of the elements in the array
{
if (sourceArr[i] != toRemove) //If the item is not equal
toReturn += sourceArr[i] + ","; //add it to the return string
}
return toReturn.substr(0, toReturn.length - 1); //remove trailing comma
}
To apply it too your var values:
var values = removeVsvVal(selectedvalues, "2");
guess im too slow but here is what i would do
<script language="javascript">
function Remove(value,replaceValue)
{ var result = ","+value+",";
result = result.replace(","+replaceValue+",",",");
result = result.substr(1,result.length);
result = result.substr(0,result.length-1);
alert(result);
}
Remove("1,2,3",2)
</script>
adding , before and after the string ensure that u only remove the exact string u want
function process(csv,valueToDelete) {
var tmp = ","+csv;
tmp = tmp.replace(","+valueToDelete,"");
if (tmp.substr(0,1) == ',') tmp = tmp.substr(1);
return tmp;
}
use splice, pop or shift. depending on your requirement.
You could also have "find" the indexes of items in your array that match by using a function like the one found here : http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
// 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20
var thirty=tmp.find(30); // Returns 9, 14, 17
var thirtyfive=tmp.find('35'); // Returns 18
var thirtyfive=tmp.find(35); // Returns 15
var haveBlue=tmp.find('blue'); // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/); // returns 8,20 (first letter starts with b)
var regexp1=tmp.find(/^b/i); // returns 8,19,20 (same as above but ignore case)
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
or
var csv_remove_val = function(s, val, sep) {
var sep = sep || ",", a = s.split(sep), val = ""+val, pos;
while ((pos = a.indexOf(val)) >= 0) a.splice(pos, 1);
return a.join(sep);
}

JQuery/JavaScript increment number

I am trying to increment a number by a given value each second and retain the formatting using JavaScript or JQuery
I am struggling to do it.
Say I have a number like so:
1412015
the number which this can be incremented by each second is variable it could be anything beween 0.1 and 2.
Is it possible, if the value which it has to be incremented by each second is 0.54 to incremenet the number and have the following output:
1,412,016
1,412,017
1,412,018
Thanks
Eef
I'm not quite sure I understand your incrementation case and what you want to show.
However, I decided to chime in on a solution to format a number.
I've got two versions of a number format routine, one which parses an array, and one which formats with a regular expression. I'll admit they aren't the easiest to read, but I had fun coming up with the approach.
I've tried to describe the lines with comments in case you're curious
Array parsing version:
function formatNum(num) {
//Convert a formatted number to a normal number and split off any
//decimal places if they exist
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//turn the string into a character array and reverse
var arr = parts[0].split('').reverse();
//initialize the return value
var str = '';
//As long as the array still has data to process (arr.length is
//anything but 0)
//Use a for loop so that it keeps count of the characters for me
for( var i = 0; arr.length; i++ ) {
//every 4th character that isn't a minus sign add a comma before
//we add the character
if( i && i%3 == 0 && arr[0] != '-' ) {
str = ',' + str ;
}
//add the character to the result
str = arr.shift() + str ;
}
//return the final result appending the previously split decimal place
//if necessary
return str + ( parts[1] ? '.'+parts[1] : '' );
}
Regular Expression version:
function formatNum(num) {
//Turn a formatted number into a normal number and separate the
//decimal places
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//reverse the string
var str = parts[0].split('').reverse().join('');
//initialize the return value
var retVal = '';
//This gets complicated. As long as the previous result of the regular
//expression replace is NOT the same as the current replacement,
//keep replacing and adding commas.
while( retVal != (str = str.replace(/(\d{3})(\d{1,3})/,'$1,$2')) ) {
retVal = str;
}
//If there were decimal points return them back with the reversed string
if( parts[1] ) {
return retVal.split('').reverse().join('') + '.' + parts[1];
}
//return the reversed string
return retVal.split('').reverse().join('');
}
Assuming you want to output a formatted number every second incremented by 0.54 you could use an interval to do your incrementation and outputting.
Super Short Firefox with Firebug only example:
var num = 1412015;
setInterval(function(){
//Your 0.54 value... why? I don't know... but I'll run with it.
num += 0.54;
console.log( formatNum( num ) );
},1000);
You can see it all in action here: http://jsbin.com/opoze
To increment a value on every second use this structure:
var number = 0; // put your initial value here
function incrementNumber () {
number += 1; // you can increment by anything you like here
}
// this will run incrementNumber() every second (interval is in ms)
setInterval(incrementNumber, 1000);
This will format numbers for you:
function formatNumber(num) {
num = String(num);
if (num.length <= 3) {
return num;
} else {
var last3nums = num.substring(num.length - 3, num.length);
var remindingPart = num.substring(0, num.length - 3);
return formatNumber(remindingPart) + ',' + last3nums;
}
}
function rounded_inc(x, n) {
return x + Math.ceil(n);
}
var x = 1412015;
x = rounded_inc(x, 0.54);

Categories

Resources