Split JSON every N - javascript

I'm trying to separate a json into several pieces n times depending on the size of the json and the limit of characters within a field. For example, if the json occupies 16000 characters I divide it by 4000 (which is the limit per field) and thus divide it into 4 pieces type string[0], string[1],string[2],string[3] and then print them to the screen.
I have this code but it always gives me the following error:
Error: Index and length must refer to a location within the string. Parameter name: length
var splitA = [];
function separatedFields(nCharacter, valueDeInfo) {
var limit = 4000;
var split = [];
var nfield = Math.ceil((nCharacter) / limit);
var begin = 0;
var end = 4000;
for (i = 0; i < nfield; i++) {
if (i == nfield - 1) {
split[i] = valueDeInfo.slice(begin, end);
begin = end;
end = nCharacter;
} else {
split[i] = valueDeInfo.slice(begin, end);
begin = end;
end = end + 4000;
}
}
return split;
}
splitA = separatedFields(nCharacter, valueDeInfo);
Write("ARRAY FIRST 4000: " + splitA[0]);
Example of input/output:
valueDeInfo = ['{"Status":"OK","RequestID":"e5517d4e-ee43-451a-bbe8-09f9fc714c21","Results":[{"CustomerKey":null,"Name":"Control","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":3,"DefaultValue":"1","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"CategoryID","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":8,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsSendable","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":2,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Name","ObjectID":null,"FieldType":"Text","IsPrimaryKey":true,"MaxLength":50,"Ordinal":0,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsRequired","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":10,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"infoDE3","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":18,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Description","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":6,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"ModifiedDate","ObjectID":null,"FieldType":"Date","IsPrimaryKey":false,"MaxLength":0,"Ordinal":7,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}']
nCharacters = valueDeinfo.length;
The correct output would be:
{"Status":"OK","RequestID":"e5517d4e-ee43-451a-bbe8-09f9fc714c21","Results":[{"CustomerKey":null,"Name":"Control","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":3,"DefaultValue":"1","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"CategoryID","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":8,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsSendable","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":2,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Name","ObjectID":null,"FieldType":"Text","IsPrimaryKey":true,"MaxLength":50,"Ordinal":0,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-0
Basically, in splitA[0] should be the first 4000 characters, in split[1] should be in the next 4000 characters and so on until you reach nCharacters

So you basically just want to split a string at a given number of characters?
You can try a regex for that
const splitAtInterval = (string, interval) => {
const r = new RegExp(`.{1,${interval}}`, 'g')
return string.match(r);
}
var text = "Some random string (in your case your JSON string)";
console.log(splitAtInterval(text, 4));
There are other options, just search google for "split string after x characters". for example https://bobbyhadz.com/blog/javascript-split-string-substrings-n-characters
Obviously, as mentioned in the comments, those strings will not be valid json anymore. You will have to fetch all the entries again and connect them via join.

Related

Is there a way to take a unique string of 256 chars, reduce it's size with JS to a unique string of 50± chars, and retain guaranteed uniqueness?

I am working on building a parser for a text file to build into a JSON object.
Presuming I have a string somewhere in the line which is a unique value: 4E183437F3FAEBC107C333CD16657661598A2A523867A4A95F6DAD4D25E191722AFFB3FFE29E287D9EB21ED8035E7666D06E65EC064D5D4B337C034459BA7CD6F72437B439329B45F15D57176122965728B36DBB455D335AA904106A29B64694507B6A0F89FBF4A166BB3BBB4DDDC1674A1DB3B7D0FD332117877C4CE56465D8
I want to use this unique identifier as a key at some level, but it's much too long to suit my tastes.
I am wondering if there is a way to create a smaller 'hash':
but not lose and information
guarantee uniqueness
be converted back to it's original
Some library/plugin?
You can create a string of smaller length by turning the 16-bit hex string into a number (with BigInt), and then by creating a new string with base, say, 10000, so that a character with character code C represents the number 'C'.charCodeAt().
Then turn it back into the original string by doing the same process in reverse.
The string length is shorter, and you've saved some bits, but it's still long:
const encode = (input) => {
let n = 0n;
[...input].forEach((char, i) => {
const code = char.charCodeAt();
const value = BigInt(code <= 57 ? code - 48 : code - 55);
n += value * (16n ** BigInt(i));
});
const base10Str = String(n);
let output = '';
for (let i = 0; i < base10Str.length; i += 4) {
output += String.fromCharCode(base10Str.slice(i, i + 4));
}
return output;
};
const decode = (encoded) => {
let base10Str = '';
[...encoded].forEach((char) => {
base10Str += String(char.charCodeAt()).padStart(4, '0'); // todo: final char may need no padding
});
let n = BigInt(base10Str);
let inputStr = '';
for (let i = 255; i >= 0; i--) {
const thisHexMult = 16n ** BigInt(i);
const thisHexDigitBigInt = n / thisHexMult; // This will automatically effectively call Math.floor
n = n % thisHexMult;
const thisHexDigit = Number(thisHexDigitBigInt);
const charCode = thisHexDigit <= 9 ? thisHexDigit + 48 : thisHexDigit + 55;
inputStr = String.fromCharCode(charCode) + inputStr;
}
console.log(inputStr);
};
const encoded = encode('4E183437F3FAEBC107C333CD16657661598A2A523867A4A95F6DAD4D25E191722AFFB3FFE29E287D9EB21ED8035E7666D06E65EC064D5D4B337C034459BA7CD6F72437B439329B45F15D57176122965728B36DBB455D335AA904106A29B64694507B6A0F89FBF4A166BB3BBB4DDDC1674A1DB3B7D0FD332117877C4CE56465D8');
console.log('Encoded length:', encoded.length);
console.log(encoded);
decode(encoded);

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

Generate string of random number that includes some number and exclude some number

I have a problem about generating string in javascript.
I have an array of number that string should contains atleast 1, and 1 number(up to 7 digits) that must not contains in a string. String length must be 7.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
I tried to generate it by random select from array, random position and random other number around selected number. Then check if string contains excluded number, generate it again.
//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//random position of number
var position = Math.floor(Math.random() * 6);
//length of other string after selected number
var afterlen = 7 - (position+2);
//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}
but doing this take too long time or sometimes freeze my browser. How should I fix it.?
edited: It's my homework about phonenumber.
final string should be like "37915002"
Edited my code again
Does that now match your needs? It has got pretty messy and I'm not sure if it's correct (I'm never sure.. xD) hope you can get some inspiration though.
// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";
// Create a third final array that is filtered
var finalList = initialList.filter(element => {
let shouldBeIncluded = true;
excludeList.forEach(excluder => {
Array.from(excluder).forEach(excluderFragment => {
if (element.includes(excluderFragment)) shouldBeIncluded = false;
});
});
if (shouldBeIncluded) return true;
});
// Check if all were excluded
if (finalList.length == 0) {
// Do error handling here
} else {
// Create the list
for (let i = 0; i < resultLength; i++) {
finalString += finalList[Math.floor(Math.random() * finalList.length)];
}
// Shorten the list because multiple digits values
finalString = finalString.slice(0, 7);
console.log(finalString);
}
You could start by filtering the unwanted number from the incNumber and doing everything the same way but on the new array
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";
var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
if we assume exclude is not a value but instead an array of values you would change the formula to
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];
var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
as some people suggested random variable may end up as undefined if we exclude all the numbers inside of incNumber, if that was the case we should add an additional check in case that happens
if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

Lossless compression run length encoding in javascript

For my assignment, I am writing the code to compress and then decompress a string through lossless compression in javascript.
For example-
Original string: heeeeelllllloo
Compressed: h1e5l6o2
Decompressed: heeeeelllllloo
This code comes out as an infinite loop, and the problem is somewhere in the compression function. Please help me find/solve the issue!
This is what I have so far:
// Read in the original text
var textToCompress = prompt("Enter the text you would like to compress: ");
runLengthEncoding(textToCompress);
function runLengthEncoding(originalText){
console.log("Original Text: " + originalText);
console.log("");
// Compress the text
console.log("COMPRESSING...");
var compressedText = compress(originalText);
console.log("Compressed: " + compressedText);
console.log("");
//Decompress the text
console.log("DECOMPRESSING...");
//var decompressedText = decompress(compressedText);
console.log("Decompressed: " + decompressedText);
console.log("");
// Make sure the compression was lossless
if(originalText == decompressedText)
{
console.log("Success! The decompressed text is the same as the original!");
}
}
// Compresses the original String by building up a new String
// with each character and how many times it repeats in a given run.
// Returns the compressed text.
function compress(original){
var result = "";
//Write your code here
for (var i = 1; i < original.length; i++){//look at each character in string
var sum = 1;
var currentChar = original.charAt(i);
//if currentchar is the first character
if (currentChar == original.charAt(0)){//isolate frist character of the string
result = currentChar;//add the currentchar to result
console.log(result);
//if currentchar is not the first character
} else if (currentChar !== original.charAt(0)) {
//if currentchar is equal to the previous character
if (currentChar == original.charAt(i-1)){
sum++;
} else {
result += sum;//add sum ot the result and reset sum to 1
sum = 1;
i = 0;
}
}
}
}
// Decompresses the compressed Run Length Encoded text back
// into the original form.
function decompress(compressedText)
{
var result = "";
for(var i = 0; i < compressedText.length; i += 2)
{
// Get the current run character
var character = compressedText.charAt(i);
// Get the run length
var runLength = parseInt(compressedText.charAt(i+1));
// Add that many repetitions of the original character to the result
for(var runIndex = 0; runIndex < runLength; runIndex++)
{
result += character;
}
}
return result;
}
First of all, don't compare the chars to find out if this char is the first one, because this would return true if the first char is repeated in the text.
The seond thing I saw, is that you set the index i to 0 every time you find a new character which leads your function to start at the beginning of the string again and will end in a deadlock.
Thats at least what I think, and I hope I could help you

JavaScript random password with specific format

I would like to generate a random password respecting the following format:
at least one uppercase character
at least one lowercase character
at least one digit
the length should be at least 6 characters
I thought about it and the only thing I could think of is some function that is quite long and ugly. Could you guys offer me a simpler, more efficient way of doing this?
PS: I'm using this function not on the client side, but on the server side, on my Node.js web application.
Here is my solution:
/**
* sets of charachters
*/
var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var lower = 'abcdefghijklmnopqrstuvwxyz'
var digit = '0123456789'
var all = upper + lower + digit
/**
* generate random integer not greater than `max`
*/
function rand (max) {
return Math.floor(Math.random() * max)
}
/**
* generate random character of the given `set`
*/
function random (set) {
return set[rand(set.length - 1)]
}
/**
* generate an array with the given `length`
* of characters of the given `set`
*/
function generate (length, set) {
var result = []
while (length--) result.push(random(set))
return result
}
/**
* shuffle an array randomly
*/
function shuffle (arr) {
var result = []
while (arr.length) {
result = result.concat(arr.splice(rand[arr.length - 1]))
}
return result
}
/**
* do the job
*/
function password (length) {
var result = [] // we need to ensure we have some characters
result = result.concat(generate(1, upper)) // 1 upper case
result = result.concat(generate(1, lower)) // 1 lower case
result = result.concat(generate(1, digit)) // 1 digit
result = result.concat(generate(length - 3, all)) // remaining - whatever
return shuffle(result).join('') // shuffle and make a string
}
console.log(password(6))
How about we place the formats into strings and we can place than into an array, then randomly chose one and randomly chose and item in that sub-array item:
var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowers = "abcdefghijklmnopqrstuvwxyz";
var digits = "01234567890";
var all = uppers + lowers + digits;
var choices = [uppers,lowers,digits];
var checks = [];
var password = "";
var ranLength = Math.ceil(Math.random()*10)+3;
for(var i=0; i<ranLength; i++){
var choice = choices[Math.ceil(Math.random()*3)-1];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
for(var i=0; i<3; i++){ // Append needed values to end
var choice = choices[i];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
password = password.split('').sort(function(){
return 0.5 - Math.random();
}).join('');
alert(password);
Edited: Sorry made a small mistake. Fixed.
Try this...
var randomstring = Math.random().toString(36).slice(-8);

Categories

Resources