I am trying to convert this string into the proper case, but it will not return the correct case. Any idea what is going wrong? (I get no errors).
var convert = "this is the end";
String.prototype.toTitleCase = function () {
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
return this.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) {
if (index > 0 && index + match.length !== title.length &&
match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
(title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
title.charAt(index - 1).search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (match.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
convert.toTitleCase();
alert(convert);
This line convert.toTitleCase(); is throwing away the result. The method is returning the correct result, but you aren't doing anything with it.
var original = "this is the end";
String.prototype.toTitleCase = function () {
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
return this.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) {
if (index > 0 && index + match.length !== title.length &&
match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
(title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
title.charAt(index - 1).search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (match.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
var titleCased = original.toTitleCase();
alert(titleCased);
Related
I am solving an algorithm question whereby it requires me to ensure that brackets, parenthesis and braces are put in the correct order or sequence.
Here is a link to the question, https://leetcode.com/problems/valid-parentheses/
An example is shown below:
Here is my code for the solution:
const isParenthesisValid = (params) => {
myList = []
lastElement = myList[myList.length - 1]
for (let i = 0; i < params.length; i++) {
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
// I get false as an answer everytime whether the pattern is correct or wrong
// false
console.log(isParenthesisValid("[()]"))
But I don't know why I get false everytime, I have compared my answer with someones else answer who did the same thing but it seems I am omitting something not so obvious.
I hope someone can point out in my code where i am getting it wrong.
Your lastElement retrieves the last element of the list at the start of the program - when there is no such element - so it's always undefined. You need to retrieve the value inside the loop instead.
const isParenthesisValid = (params) => {
myList = []
for (let i = 0; i < params.length; i++) {
const lastElement = myList[myList.length - 1]
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
console.log(isParenthesisValid("[()]"))
Or, a bit more readably:
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
const lastElement = openDelimiters[openDelimiters.length - 1];
if (delim === "(" || delim === "[" || delim === "{") {
openDelimiters.push(delim)
} else if ((delim === ")" && lastElement === "(") || (delim === "]" && lastElement === "[") || (delim === "}" && lastElement === "{")) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))
Another approach, linking each delimiter with an object:
const delims = {
')': '(',
'}': '{',
']': '[',
};
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
if ('([{'.includes(delim)) {
openDelimiters.push(delim)
} else if (')]}'.includes(delim) && openDelimiters[openDelimiters.length - 1] === delims[delim]) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))
I am running this code on ~479k words and it is taking a very long time:
const fs = require('fs')
const words = fs.readFileSync('dicts/eng.csv', 'utf-8')
.split(/\n/)
.filter(x => x && !x.match('-') && !x.match(/[A-Z]/))
.reduce((m, x) => {
m[x] = true
return m
}, {})
for (let word in words) {
for (let form in words) {
if (form.indexOf(word) == 0) {
if (form.length == word.length + 2 && form.endsWith('ed')) {
delete words[form]
} else if (form.length == word.length + 4 && form.endsWith('tion')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('ing')) {
delete words[form]
} else if (form.length == word.length + 2 && form.endsWith('er')) {
delete words[form]
} else if (form.length == word.length + 2 && form.endsWith('or')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('est')) {
delete words[form]
} else if (form.length == word.length + 1 && form.endsWith('s')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('ers')) {
delete words[form]
} else if (form.length == word.length + 4 && form.endsWith('ings')) {
delete words[form]
}
}
}
}
fs.writeFileSync('dicts/eng.out.csv', Object.keys(words).sort().join('\n'))
How can I speed this up to take only a fraction of the time, on the order of a second or two or whatever is more realistic?
Is there some data structure I need to convert this list into that is better suited to a faster algorithm?
this may work:
const fs = require('fs')
let words = fs.readFileSync('dicts/eng.csv', 'utf-8')
.split(/\n/)
.filter(x => x && !x.match('-') && !x.match(/[A-Z]/)).sort()
let out = new Set, root = words[0];
for (let word of words) {
if (!word.startsWith(root))
root = word;
word = root === word ? root : word
.replace(/(ed|tion|ing|er|or|est|s|ers|ings)$/, '')
out.add(word);
}
fs.writeFileSync('dicts/eng.out.csv', [...out].join('\n'));
I am trying to make the input date of birth mask in angular and format of date is dd/mm/yyyy ,but it not set and return the input according to our requirement input value.
my code given below.
<input type="text" placeholder="{{timePlaceholder}}" (focus)="showlable()" (focusout)="hidelable()" (keypress)="this.value =fixDatePattern($event);">
currentDate:any = "";
currentLength:any ="";
lastNumberEntered:any ="";
transformedDate:any="";
dateCountTracker:any="";
fixDatePattern(event) {
this.currentDate = event.target.value;
this.currentLength = this.currentDate.length;
this.lastNumberEntered = this.currentDate[this.currentLength - 1];
if (this.currentLength > 10) {
return this.currentDate.substring(0, 10);
}
if (this.currentLength == 1 && this.currentDate > 1) {
this.transformedDate = "0" + this.currentDate + '/';
this.dateCountTracker = 2;
this.currentLength = this.transformedDate.length;
return this.transformedDate;
} else if (this.currentLength == 4 && this.currentDate[3] > 3) {
this.transformedDate = this.currentDate.substring(0, 3) + "0" + this.currentDate[3] + '/';
this.dateCountTracker = 5;
this.currentLength = this.transformedDate.length;
return this.transformedDate;
} else if (this.currentLength == 2 && (this.dateCountTracker != 2 && this.dateCountTracker != 3)) {
this.dateCountTracker = this.currentLength;
return this.currentDate + '/';
} else if (this.currentLength == 5 && (this.dateCountTracker != 5 && this.dateCountTracker != 6)) {
this.dateCountTracker = this.currentLength;
return this.currentDate + '/';
}
this.dateCountTracker = this.currentLength;
return this.currentDate;
}
<input placeholder="mm/dd/yyyy" (input)="KeyUpCalled($event.target.value)" maxlength="10" [(ngModel)]="inputValue">
inputValue;
KeyUpCalled(value){
var dateCountTracker;
var currentDate = value;
var currentLength = currentDate.length;
var lastNumberEntered = currentDate[currentLength - 1];
if (currentLength > 10) {
var res = currentDate.substring(0, 10)
this.inputValue = res;
return this.inputValue
}
if (currentLength == 1 && currentDate > 1) {
var transformedDate = "0" + currentDate + '/';
dateCountTracker = 2;
currentLength = transformedDate.length;
this.inputValue = transformedDate;
return this.inputValue;
} else if (currentLength == 4 && currentDate[3] > 3) {
var transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
dateCountTracker = 5;
currentLength = transformedDate.length;
this.inputValue = transformedDate;
return this.inputValue;
} else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
dateCountTracker = currentLength;
this.inputValue = currentDate + '/'
return this.inputValue;
} else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
dateCountTracker = currentLength;
// return currentDate + '/';
this.inputValue = currentDate + '/'
return this.inputValue;
}
dateCountTracker = currentLength;
this.inputValue = currentDate;
}
Using primeng :
in app module :
import {InputMaskModule} from 'primeng/inputmask';
#NgModule({
imports: [
...
InputMaskModule,
FormsModule
],
for the HTML :
<div class="p-col-12 p-md-6 p-lg-4">
<span>Date</span>
<p-inputMask mask="99/99/9999" [(ngModel)]="val3" placeholder="99/99/9999" slotChar="mm/dd/yyyy"></p-inputMask>
</div>
source : https://www.primefaces.org/primeng/inputmask
I have the two functions match and and total working properly. I want the function total project match to divide the first function over the second function multiply times 100. the last function isn't working!
Here is my code so far :
matchContribution.subscribe(function (newValue) {
if (newValue != undefined && newValue != '') {
matchContribution(formatInt(newValue));
var dataValue = Number(matchContribution().replace(/\,/g, ''));
if (dataValue > 999999999999.99 || dataValue < 0) {
matchContribution('');
}
if (loading == false) {
sendCommand('SAVE');
}
}
});
var totalProjectCost = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if (grantRequest() != '' && grantRequest() != undefined) {
hasUserInput = true;
total = total + Number(String(grantRequest()).replace(/\,/g, ''));
}
if (matchContribution() != '' && matchContribution() != undefined) {
hasUserInput = true;
total = total + Number(String(matchContribution()).replace(/\,/g, ''));
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatInt(total);
}
});
var totalProjectMatch = matchContribution()/totalProjectCost();
if(totalProjectMatch>=0)
totalProjectMatch = Math.floor(totalProjectMatch);
else
totalProjectMatch = Math.ceil(totalProjectMatch);
var totalProjectMatch = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if ((grantRequest() != '' && grantRequest() != undefined) && (matchContribution() != '' && matchContribution() != undefined) && (totalProjectCost() != '' && totalProjectCost() != undefined)) {
hasUserInput = true;
total = Number(String(matchContribution()).replace(/\,/g, '')) / Number(String(totalProjectCost()).replace(/\,/g, ''));
total = total * 100;
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatNumber(total);
}
});
I solved the problem! Thanks a lot! Hope that helps other people.
I want to optimise and reduce my code to increase performance and correct-ability of it. With those two different functions below I can successfuly move a Google Map Marker on a map forward and backward using a pathIndex, calcuted on an array of GPS coordinates [I didn't include this section of code since I think it's not releated to this question but I can and will post it if needed].
This is my code:
1st function:
function animate() {
if (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED) {
googleMapsMarker.setPosition(coord[pathIndex]);
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
timerHandler = setTimeout("animate(" + pathIndex + ")", 1000);
}
}
2nd function:
function animateRewind() {
if (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED) {
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
timerHandler = setTimeout("animateRewind(" + pathIndex + ")", 1000);
}
}
As you can see those two functions shares a lot of portions of code and it think that they can be replaced with a single one for this reason but I can't figure out how to do this.
So, is it possible to create a single function to manage those two different animations?
I hope I didnt miss something...
function animate(pathIndex, dir) {
var animateDir = (pathIndex < coord.length
&& mapAnimationStatus != PLAY_PAUSED && dir == 'f')
? dir
: (pathIndex >= 0
&& mapAnimationStatus != PLAY_PAUSED && dir == 'r')
? dir : "error";
if (animateDir === "r") { googleMap.panTo(coord[pathIndex]); }
if (animateDir !== 'error') { googleMapsMarker.setPosition(coord[pathIndex]); }
if (animateDir === "f") {
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
}
if (animateDir !== 'error') {
if (pathIndex == coord.length || pathIndex == 0) {
pause();
pathIndex = animateDir === "f" ? 0 : pathIndex;
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex = animateDir === "f" ? pathIndex - 1 : pathIndex;
timerHandler = setTimeout("animate(" + pathIndex + "," + animateDir + ")", 1000);
}
}
You can try this :
function ConcatenateFunctions() {
if(mapAnimationStatus != PLAY_PAUSED){
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex < coord.length) {
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
}else if (pathIndex >= 0) {
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
}
timerHandler = setTimeout("ConcatenateFunctions(" + pathIndex + ")", 1000);
}
}
Hope it will help !