How to get string converted to array? - javascript

I am kind of new to this, but this is giving me a headache.
Heres my code what i am trying to solve:
function parseComponents(data: any, excelAttributesArray: string[]) {
let confs = "";
let isValues = false;
let listValues = "";
if (!data) return confs;
if (data["Part"]) {
const part = data["Part"];
excelAttributesArray.forEach((attribute) => {
let attributeValue = part[attribute];
if (attributeValue !== null) isValues = true;
if (attributeValue !== null && attributeValue.Value) {
attributeValue = attributeValue.Value;
}
listValues += attributeValue + ",";
});
const number = part["Number"];
if (isValues) {
confs += `${listValues}${number}`;
}
}
if (data["Components"] && data["Components"].length > 0) {
for (let i = 0; i < data["Components"].length; i++) {
const tmp = parseComponents(
data["Components"][i],
excelAttributesArray
);
if (tmp && tmp.length > 0)
confs += (confs.length > 0 ? "|" : "") + tmp;
}
}
return confs;
}
The confs value is returned as a string. How do i get it return as array?

Related

find the overlap between two strings

I have a string and need to check with and get whether the following strings overlap with the start and end of my target string:
target string: "click on the Run"
search strings: "the Run button to", "code and click on"
Apparently:
"the Run button to" is overlapped at the end of target "click on the Run"
"code and click on" is overlapped at the start of target "click on the Run"
Both, "the Run" and "click on" will be the desired results.
I have come up with a function to check and get the overlapped results for the cases at the start and at the end separately.
Question:
But my code could not be able to get the expected results only if I know how the search string overlapped with the target string in the very first place. And how can I combine the searched results in one go as well?
function findOverlapAtEnd(a, b) {
if (b.length === 2) {
return "";
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.endsWith(b)) {
return b;
}
return findOverlapAtEnd(a, b.substring(0, b.length - 1));
}
function findOverlapAtStart(a, b) {
if (b.length === 2) {
return "";
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.startsWith(b)) {
return b;
}
return findOverlapAtStart(a, b.substring(1));
}
console.log(findOverlapAtEnd("click on the Run", "the Run button to"))
console.log(findOverlapAtStart("click on the Run", "code and click on"))
edited:
case in the middle is also considered, e.g.:
target string: "click on the Run"
search strings: "on the"
Return value: "on the"
You may try this
function findOverlapAtEnd(a, b, min) {
if (b.length <= min) {
return '';
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.endsWith(b)) {
return b;
}
return findOverlapAtEnd(a, b.substring(0, b.length - 1), min);
}
function findOverlapAtStart(a, b, min) {
if (b.length <= min) {
return '';
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.startsWith(b)) {
return b;
}
return findOverlapAtStart(a, b.substring(1), min);
}
const GetOverlappingSection = (target, search, min) => {
if (target.length < search.length) {
const tmp = target;
target = search;
search = tmp;
}
let overlap1 = findOverlapAtStart(target, search, min);
if (overlap1.length === 0) {
overlap1 = findOverlapAtEnd(target, search, min);
}
return overlap1;
};
const removeEmptyKeyword = overlap => {
let tmpFinaloverlap = [];
overlap.forEach((key, idx) => {
if (!(key.trim().length === 0)) {
tmpFinaloverlap = [...tmpFinaloverlap, key];
}
});
return tmpFinaloverlap;
};
// let overlap = ['click on','the Run']
const GetOverlappingOfKeyowrd1And2 = (keywordSet1, keywordSet2,min) => {
let resultSetoverlap = [];
let tmpresultSetoverlap = [];
keywordSet1.forEach(key =>
keywordSet2.forEach(k2 => {
tmpresultSetoverlap = [
...tmpresultSetoverlap,
GetOverlappingSection(key, k2, min),
];
})
);
// get the resultSetoverlap
tmpresultSetoverlap.forEach(element => {
if (element.length > 0) {
resultSetoverlap = [...resultSetoverlap, element];
}
});
return resultSetoverlap;
};
const min = 2;
//To handle overlapping issue in overlapping set, that casuing
overlap.forEach((key, idx) => {
if (idx < overlap.length - 1) {
for (let i = idx + 1; i < overlap.length; i++) {
console.log(`key: ${key}`);
console.log(`search: ${overlap[i]}`);
let overlapSection = GetOverlappingSection(key, overlap[i], min);
if (overlapSection.length > 0) {
console.log(`overlapSection: ${overlapSection}`);
overlap[idx] = overlap[idx].replace(overlapSection, '');
}
}
}
});
overlap = removeEmptyKeyword(overlap);
console.log(overlap);
overlap.forEach(key => {
keywordSet2 = keywordSet2.map((k1, idx) => {
console.log(`checking overlap keyword:'${key}' in '${k1}'`);
return k1.replace(key, '');
});
});
overlap.forEach(key => {
keywordSet1 = keywordSet1.map((k1, idx) => {
console.log(`checking overlap keyword:'${key}' in '${k1}'`);
return k1.replace(key, '');
});
});
keywordSet2 = removeEmptyKeyword(keywordSet2);
keywordSet1 = removeEmptyKeyword(keywordSet1);
overlap.forEach(key => {
text = text.replace(key, `$#k1k2$&$`);
});
keywordSet1.forEach(key => {
text = text.replace(key, `$#k1$&$`);
});
keywordSet2.forEach(key => {
text = text.replace(key, `$#k2$&$`);
});
console.log(`ResultSetoverlap after processing:${text}`);
Because I need to decompress and I find these logic puzzles fun, here's my solution to the problem...
https://highdex.net/begin_end_overlap.htm
You can view source of the page to see JavaScript code I used. But just in case I ever take that page down, here's the important function...
function GetOverlappingSection(str1, str2, minOverlapLen = 4) {
var work1 = str1;
var work2 = str2;
var w1Len = work1.length;
var w2Len = work2.length;
var resultStr = "";
var foundResult = false;
var workIndex;
if (minOverlapLen < 1) { minOverlapLen = 1; }
else if (minOverlapLen > (w1Len > w2Len ? w2Len : w1Len)) { minOverlapLen = (w1Len > w2Len ? w2Len : w1Len); }
//debugger;
//we have four loops to go through. We trim each string down from each end and see if it matches either end of the other string.
for (var i1f = 0; i1f < w1Len; i1f++) {
workIndex = work2.indexOf(work1);
if (workIndex == 0 || (workIndex != -1 && workIndex == w2Len - work1.length)) {
//we found a match!
foundResult = true;
resultStr = work1;
break;
}
work1 = work1.substr(1);
if (work1.length < minOverlapLen) { break; }
}
if (!foundResult) {
//debugger;
//reset the work vars...
work1 = str1;
for (var i1b = 0; i1b < w1Len; i1b++) {
workIndex = work2.indexOf(work1);
if (workIndex == 0 || (workIndex != -1 && workIndex == w2Len - work1.length)) {
//we found a match!
foundResult = true;
resultStr = work1;
break;
}
work1 = work1.substr(0, work1.length - 1);
if (work1.length < minOverlapLen) { break; }
}
}
if (!foundResult) {
//debugger;
//reset the work vars...
work1 = str1;
for (var i2f = 0; i2f < w2Len; i2f++) {
workIndex = work1.indexOf(work2);
if (workIndex == 0 || (workIndex != -1 && workIndex == w1Len - work2.length)) {
//we found a match!
foundResult = true;
resultStr = work2;
break;
}
work2 = work2.substr(1);
if (work2.length < minOverlapLen) { break; }
}
}
if (!foundResult) {
//debugger;
//reset the work vars...
work2 = str2;
for (var i2b = 0; i2b < w2Len; i2b++) {
workIndex = work1.indexOf(work2);
if (workIndex == 0 || (workIndex != -1 && workIndex == w1Len - work2.length)) {
//we found a match!
foundResult = true;
resultStr = work2;
break;
}
work2 = work2.substr(0, work2.length - 1);
if (work2.length < minOverlapLen) { break; }
}
}
return resultStr;
}
Hopefully that's helpful.

How can I stop this from writing a value to all dictionaries? (Javascript)

Intro
So I have stumbled across this problem yesterday, and I've been stumped trying to figure this out myself. I only have this problem with JavaScript.
Problem
I've been creating a programming language with JS since the start of this week, and I was enjoying myself the entire week making it. The problem here is that when I carry dictionaries across functions, it has some problems reading and writing into those dictionaries. When I check the console logs, I see that not just the dictionary in the function was written, but all of the instances of that dictionary were written.
Code
Here is the code to graph.js:
function codeToArray(code) {
let codeArray = {commands:[], vars:{x:{value:0, read_only:true},y:{value:0, read_only:false}}};
let commands = code.split("\n");
for (i = 0; i < commands.length; i++) {
let command = commands[i];
let inputs = command.split(" ");
if (inputs[0].toLowerCase() !== ";") {
// Arithmetics
if (inputs[0].toLowerCase() === "+") { // Addition
codeArray.commands.push({name:"add", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "-") { // Subtraction
codeArray.commands.push({name:"subtract", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "*") { // Multiplication
codeArray.commands.push({name:"multiply", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "/") { // Division
codeArray.commands.push({name:"divide", variable:inputs[1], value:inputs[2], syntax_id:1});
}
// I/O
else if (inputs[0].toLowerCase() === ":") { // Set
codeArray.commands.push({name:"set", variable:inputs[1], value:inputs[2], syntax_id:1});
}
// Conditional Statements
else if (inputs[0].toLowerCase() === "if") { // If Statement
let ifCommand = "";
for (j = 4; j < inputs.length; j++) {
if (j > 4) {
ifCommand += " " + inputs[j];
} else {
ifCommand += inputs[j];
}
}
let ifCommandArray = codeToArray(ifCommand).commands[0];
codeArray.commands.push({name:"if", value1:inputs[1], condition:inputs[2], value2:inputs[3], command:ifCommandArray, syntax_id:2});
}
}
}
return codeArray
}
function parseValue(value, variables) {
let return_value = value;
console.log(value);
console.log(variables);
if (value.charAt(0) === "$") {
let variable_name = return_value.substring(1, value.length);
console.log(variable_name);
let variable = variables[variable_name];
console.log(variable);
if (variable === undefined) {
return_value = NaN;
} else {
return_value = variable.value;
}
} else {
return_value = parseFloat(value);
}
console.log(return_value);
return return_value
}
function runCodeArray(commands, variables) {
for (i = 0; i < commands.length; i++) {
let command = commands[i];
if (command.syntax_id === 1) { // Simple Syntax (Variable Value Syntax)
if (command.name === "add") { // Addition
let variable = variables[command.variable];
if (variable === undefined) {
let error_message = `Variable cannot be found (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
if (variable.read_only === true) {
let error_message = `A read-only variable was trying to be written (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
let value = parseValue(command.value, variables);
if (value === NaN) {
let error_message = `The value parameter is invalid (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
variable.value += value;
} else if (command.name === "set") { // Set
let variable = variables[command.variable];
if (variable === undefined) {
variables[command.variable] = {value:0, read_only:false};
variable = variables[command.variable];
}
if (variable.read_only === true) {
let error_message = `A read-only variable was trying to be written (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
let value = parseValue(command.value, variables);
if (value === NaN) {
let error_message = `The value parameter is invalid (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
variable.value = value;
}
}
}
return {commands:commands, variables:variables, return_message:true};
}
var url_string = ...graph.html?pattern=%3A+a+42%0D%0A%3A+b+%24a%0D%0A%3A+c+%24b%0D%0A // window.location.href;
var url = new URL(url_string);
var pattern = url.searchParams.get("pattern");
let codeArray = codeToArray(pattern);
// console.log(codeArray);
let codeArrayOut = runCodeArray(codeArray.commands, codeArray.vars); // Will return true in return_message if everything is good, and will return a string in return_message if an error occurs.
// console.log(codeArrayOut);
if (codeArrayOut.return_message !== true) {
alert("Error: " + codeArrayOut.return_message);
}
Sorry if the code is too long, boring or messy for you to read. Here is the function that's causing the most problems:
function parseValue(value, variables) {
let return_value = value;
console.log(value);
console.log(variables);
if (value.charAt(0) === "$") {
let variable_name = return_value.substring(1, value.length);
console.log(variable_name);
let variable = variables[variable_name];
console.log(variable);
if (variable === undefined) {
return_value = NaN;
} else {
return_value = variable.value;
}
} else {
return_value = parseFloat(value);
}
console.log(return_value);
return return_value
}
Outro
I'm still learning in JavaScript, so I hope that you can solve this problem (because I can't).

convert a string containing boolean values to a boolean

If I have this ;
var a = "(true && false) && true && false"
And if I want to evaluate this string , what are the options ?
If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?
If not, what is the most performant way of parsing it ?
EDIt :
By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :
var a = "(true && false) || (true && (true && false)) && true && false"
FIY :
I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?
EDIT : the original problem :
var a = function(){ return false} // all of them always return a boolean
var b = function(){ return true}
var c = function(){ return true}
var d = function(){ return false}
var conditions = "(a && b) && c && d"
I can't change the above code , I need to parse it, I need the condition to be evaluated ;
function ExecuteJavascriptString() {
var n = 0;
var s = "(true || false) || (true || (true || false)) && true";
var ifstate = " if (" + s + ") { console.log('done'); } ";
setTimeout(ifstate, 1);
}
ExecuteJavascriptString()
I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:
var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";
console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input
function evalBoolStr(str) {
if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
return eval(str);
}
return 'Invalid input';
}
An attempt at actually writing a parser for boolean strings:
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";
console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
function a() {
return false;
}
function b() {
return true;
}
function c() {
return true;
}
function d() {
return false;
}
Usage would then simply be parseBoolStr('true && false'); //false

Creating an array that tells if a given number is smaller than 10

I am trying to make this work, I don't know what is wrong with it.
It used to work with only 3 variables, when I made it longer it stoped and now I cannot make it work even with only 3. Now it gives me "Undefined Undefined Undefined".
What I want is to crate an alarm in a way that it shows the name of whatever has gone under 10. The fields it is comparing from are calculation fields with the REPEATABLESUM() code.
var choice1 = '';
var choice2 = '';
var choice3 = '';
var choice4 = '';
var choice5 = '';
var choice6 = '';
var choice7 = '';
var choice8 = '';
var choice9 = '';
var choice10 = '';
var choice11 = '';
var choice12 = '';
var choice13 = '';
var choice14 = '';
var choice15 = '';
var choice16 = '';
var choice17 = '';
var choice18 = '';
var choice19 = '';
var choice20 = '';
var choice21 = '';
var choice22 = '';
var choice23 = '';
var choice24 = '';
if (NUM($stock_coliblue_24) < 10) {
choice1 = LABEL('coliblue');
}
if (NUM($stock_absorvent_pads) < 10) {
choice2 = LABEL('absorvent_pads');
}
if (NUM($stock_micro_filters) < 10) {
choice3 = LABEL('micro_filters');
}
if (NUM($stock_alkaphotalkalinity) < 10) {
choice4 = LABEL('alkaphot');
}
if (NUM($stock_ammonia) < 10) {
choice5 = LABEL('ammonia');
}
if (NUM($stock_calcicol_calcium_hardness) < 10) {
choice6 = LABEL('calcicol');
}
if (NUM($stock_chloridol_nacl) < 10) {
choice7 = LABEL('chloridol');
}
if (NUM($stock_free_chlorine_dpd1) < 10) {
choice8 = LABEL('chlorine_free_dpd1');
}
if (NUM($stock_total_chlorine_dpd3) < 10) {
choice9 = LABEL('chlorine_total_dpd2');
}
if (NUM($stock_free_copper_n1) < 10) {
choice10 = LABEL('copper_free_n1');
}
if (NUM($stock_total_copper_n2) < 10) {
choice11 = LABEL('copper_total_n2');
}
if (NUM($stock_fluoride) < 10) {
choice12 = LABEL('fluoride');
}
if (NUM($stock_hardicol_total_hardness) < 10) {
choice13 = LABEL('hardicol');
}
if (NUM($stock_iron_hr) < 10) {
choice14 = LABEL('iron_hr');
}
if (NUM($stock_iron_mr) < 10) {
choice15 = LABEL('iron_mr');
}
if (NUM($stock_magnecol_magnesium) < 10) {
choice16 = LABEL('magnecol');
}
if (NUM($stock_manganese) < 10) {
choice17 = LABEL('manganese');
}
if (NUM($stock_nitratest_nitrate) < 10) {
choice18 = LABEL('nitratest');
}
if (NUM($stock_nitricol_nitrite) < 10) {
choice19 = LABEL('nitricol');
}
if (NUM($stock_phosphate) < 10) {
choice20 = LABEL('phosphate');
}
if (NUM($stock_potassium) < 10) {
choice20 = LABEL('potassium');
}
if (NUM($stock_silica) < 10) {
choice21 = LABEL('silica');
}
if (NUM($stock_sulphate) < 10) {
choice22 = LABEL('sulphate');
}
if (NUM($stock_sulphitest_sulphite) < 10) {
choice23 = LABEL('sulphitest');
}
if (NUM($stock_zinc) < 10) {
choice24 = LABEL('zinc');
}
if (choice1 == null && choice2 == null && choice3 == null && choice4 == null && choice5 == null && choice6 == null && choice7 == null && choice8 == null && choice9 == null && choice10 == null && choice11 == null && choice12 == null && choice13 == null && choice14 == null && choice15 == null && choice16 == null && choice17 == null && choice18 == null && choice19 == null && choice20 == null && choice21 == null && choice22 == null && choice23 == null && choice24 == null) {
SETRESULT('');
} else {
CONCAT (choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8 + choice9 + choice10 + choice11 + choice12 + choice13 + choice14 + choice15 + choice16 + choice17 + choice18 + choice19 + choice20 + choice21 + choice22 + choice23 + choice24);
}
user array
var choice = [];
var concatStr = "";
if (NUM($stock_coliblue_24) < 10) {
choice[0] = 'coliblue';
}
if (NUM($stock_absorvent_pads) < 10) {
choice[1] = 'absorvent_pads';
}
if (choice.length == 0){
SETRESULT('');
} else {
concatStr = arr.join(" ");
}
var choice = []; /*Using array notation instead of using 24 separate variables*/
var concatStr = "";
if (NUM($stock_coliblue_24) < 10) {
choice[0] = 'coliblue'; /*storing value in array rather than in variables*/
}
,..
,..
if (NUM($stock_zinc) < 10) {
choice[23] = LABEL('zinc');
}
/* Using for loop to iterate through array to check for null values. This is easier than having '==' null check for all 24 variables*/
for(var i=0;i<24;i++) {
if(choice[i] == null) {
SETRESULT('');
break;
}
}
/*If none of the values are null, then concat the array elements. Array.join is so easier than concatenating 24 string variables.*/
if(choice.length==24) {
concatStr = choice.join(" ");
}
Hope this explains.

Angularjs str_pad_left

Is there any angularjs or javascript function similiar to PHP str_pad_left ?
I could not get any result no input was written on screen.
Also i did not now if is it valid to pass the first parameter inside : {{}}.
I try use javascript str_pad function :
<script>
var num = str_pad({{ item.ID }}, 10,'','STR_PAD_LEFT')
document.write(num);
console.log('num '+num);
</script>
From this script :
function str_pad(input, pad_length, pad_string, pad_type) {
var half = '',
pad_to_go;
var str_pad_repeater = function(s, len) {
var collect = '',
i;
while (collect.length < len) {
collect += s;
}
collect = collect.substr(0, len);
return collect;
};
input += '';
pad_string = pad_string !== undefined ? pad_string : ' ';
if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') {
pad_type = 'STR_PAD_RIGHT';
}
if ((pad_to_go = pad_length - input.length) > 0) {
if (pad_type === 'STR_PAD_LEFT') {
input = str_pad_repeater(pad_string, pad_to_go) + input;
} else if (pad_type === 'STR_PAD_RIGHT') {
input = input + str_pad_repeater(pad_string, pad_to_go);
} else if (pad_type === 'STR_PAD_BOTH') {
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
input = half + input + half;
input = input.substr(0, pad_length);
}
}
return input;
}

Categories

Resources