how to make an ⇒ and a ⇔ (logic connectives)? - javascript

I'm trying to evaluate this string:
var proposition = "(true&&false)⇒!true";
console.log(eval(proposition));
but that does not work because this "⇒" character, that is an unrecognized logic connective.
I was reading this answer post Boolean Implication but I still can't apply that to what I need.
I have this two functions that returns the implication and biconditional boolean result between two booleans values:
function Implication(v1,v2){
return (!v1)||v2; //implication formula
}
function Biconditional(v1,v2){
if(v1==v2) return true; //biconditional formula
else return false;
}
And I can apply that functions for a specific logical proposition like this:
var proposition = "(true&&false)⇒!true";
var pars = proposition.split("⇒")
var result = Implication(eval(pars[0]),eval(pars[1]))
console.log(result)
And that works, but what if I have something like: "((true⇔true)&&false)⇒false⇔true||false" or any other convination?

Related

How to find whole substring in string?

I have a string and I have to check if that string contains defined substring I need to do some work and otherwise, I should return some error.
I have the following code:
function isContains(myString) {
let subString = 'test1234';
if(myString.includes(subString)) {
// to do some work
} else {
// return some error.
}
}
but the problem is if myString = 'my-string-test1-rrr' its condition return true.
How can I get true only in case when the whole subString was included in myString?
Use indexOf() instead.
function isContains(myString) {
let subString = 'test1234';
if(myString.indexOf(subString) > -1) {
// to do some work
} else {
// return some error.
}
}
you can use regex to check if that value is present are not;
example 1
without containing the specific string
var test = 'my-string-test1-rrr';
console.log(' test --- ', test.match(/test1234/g))
example 2
contains the specific string
var test = 'my-string-test1234-rrr';
console.log(' test --- ', test.match(/test1234/g))
It is highly recommended to use includes() over indexOf() and further indexOf returns the index of the occurrence where you would prefer an immediate answer - false / true if that substring is found inside the searched string.
Your function does exactly what you are asking. I would suggest to isolate the retrieval of this function and make it purer like so, then when you have the return boolean value you could utilize it after to run whatever logic you wish. This way you keep this function pure and separate your concerns better.
I also believe it would be easier for you to debug your issue if you isolate this functions like In the example I provided.
function isContains(myString) {
let subString = 'test1234';
let isContains = false;
if(myString.includes(subString)) {
isContains = true;
} else {
isContains = false;
}
return isContains;
}
You could use it like so in a later phase in your code:
const myString = 'my-string-test1-rrr';
let shouldRunOtherLogic = isContains(myString);
if (shouldRunOtherLogic) {
// to do some work
} else {
// return some error.
}
Hope I could help, if there's anything further you may need feel free to let me know.

Best/efficent way to remember last function result

I got used to using bind to remember the last result of function and to keep track to be able to use the last result for the next result. For instance to concat or join last string to a new string without using outer variables:
function remStr(outStr){
return function c(lastStr,newStr){
if(!newStr)return lastStr;
var all = lastStr+newStr;
return c.bind(null,all);
}.bind(null,outStr);
}
var str = remStr('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow
The problem is that I want to call remStr several times and so bind came into play. But can it be done better or just differently, maybe it turns out that for one case an approach fulfills a task better than remStr?
If I understand your intention correctly, how about just using the closure?
function remStr(outStr) {
return function c(newStr) {
if (!newStr) return outStr;
outStr += newStr;
return c;
}
}
var str = remStr('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow
As mentioned by Tomalak in the comments, JavaScript strings are immutable, so if you intend to use large or many strings, you will probably want to buffer them in an array.
function remStr(outStr) {
var buffer = [outStr || ''];
return function c(newStr) {
if (!newStr) return buffer.join('');
buffer.push(newStr);
return c;
}
}
var str = remStr('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow
You shouldn't be using Function.bind here at all. You can cache the arguments. And then join it.
This approach is widely known as functions are also objects and can have properties. Function.bind is used to change the context of the given function and that isn't what we want.
function concat(word){
return function fn(anWord){
if(!anWord) return fn.words.join("");
(fn.words || (fn.words = [word])).push(anWord);
}
}
Now you can use it like below:
var str = concat("stack");
str("over");
str("flow");
console.log(str()); // "stackoverflow"

How do I ensure an array gets sorted in JavaScript?

I am trying to do something like this with very large arrays (5k+):
exports.sortedArray = function(req,res){
var fs = require("fs");
var path = 'somePath.txt';
//async
fs.readFile(path, function(err,f){
var incoming = f.toString();
//var returner = csvarray(incoming);
var returner = incoming.split("\n");
for (var i=0;i<returner.length;i++){
returner[i] = returner[i].split(",");
}
returner.sort(function(a,b){
return b[3]-a[3];
});
res.json(returner);
})
}
The file gets read. The csv string is converted to an array. But the function returns the array before sorting it.
The code above is the ajax response from a server running node.js and express. I have the same problem if I sort the array on the other end of the Ajax call, i.e. 'console.log(result);' in the browser instead of 'res.json' on the server. The printed array is still unsorted.
I've tried several hacky solutions. If I stall the return (such as with setTimeout), I get the sorted array. But I'd rather have the results when ready, such as with a callback. I just can't figure out how to attach a callback to a sort function. I feel like I'm missing something fundamental.
Array.sort may behave oddly when you return a non-comparable item such as NaN. One common way to ensure you don't return NaN in sorts like yours is to check if a and b are finite
I would suggest you rewrite your sort similar to:
returner.sort(function(a,b){
var aFinite = isFinite(a[3]), bFinite = isFinite(b[3]);
if(!aFinite || !bFinite) {
if(bFinite) return 1;
if(aFinite) return -1;
return 0;//both not finite
}
return b[3]-a[3];
});
I think this should work too
returner.sort(function(a,b){
var aFinite = isFinite(a[3]), bFinite = isFinite(b[3]);
return aFinite && bFinite ? b[3]-a[3] : aFinite-bFinite;//noting that a true - false = 1, false - true = -1 etc
});

Use Javascript or jQuery to create an array from an array

Assume you have an array:
var arrStateCityAll=['CA_Alameda','CA__Pasadena','CA_Sacramento','NY_Albany','NY_Buffalo','NY_Ithaca']
Is there an easy way using javascript and/or jQuery to filter the arrStateCityAll to get a new array (a subset of arrStateCityAll); something like this:
// return's ['CA_Alameda','CA__Pasadena','CA_Sacramento']
var arrStateCityCA=FilterArray('CA',arrStateCityAll);
Likely you want to do a regex on each item. You can do this with jQuery's grep function.
http://api.jquery.com/jQuery.grep/
You can use javascript's Array.filter.
var arrStateCityAll = ['CA_Alameda','CA__Pasadena','CA_Sacramento','NY_Albany','NY_Buffalo','NY_Ithaca']
var arrStateCityCA = arrStateCityAll.filter( function (element) {
return element.indexOf("CA_") == 0;
});
The mozilla documentation linked to above has a solution for browsers that don't implicitly support filter.
This should work.
var arrStateCityCA = [];
for (var i = 0;i<arrStateCityAll.length;i++){
if (arrStateCityAll[i].substr(0,2) == 'CA'){
arrStateCityCA.push(arrStateCityAll[i]);
}
}
You could use jQuery.grep
var arrStateCityCA =
$.grep(arrStateCityAll,function(el,i){return (el.substring(0,2)=='CA')});
Demo at jsfiddle
To implement you actual FilterArray function as shown in your post you could do
function FilterArray(state,arr){
return $.grep(arr,
function(el,i) {return (el.substring(0,2)==state)}
);
}
This makes a few assumptions.
State is always 2 chars.
State is always the first 2 chars.
And of course remember case-sensitivity (this function is case sensitive) ie 'CA' not equal to 'Ca'.
if you are going to have an undescore between your state and city name, you can split on the underscore and test against the first array value
function getSubSetByState(set,state) {
var result = [];
for(var i=0,l=set.length;i<l;++i) {
if(set[i].split('_')[0] === state) {
result.push(set[i]);
}
}
return result;
}
Use if by giving it the set of places, and then the state you are searching for.

adding chr to the number Prototype

I have the following function:
var chr = function(X) {
return String.fromCharCode(X)
}
But I would like to use i.chr() instead of chr(i).
Q: How do I add chr() to the number prototype?
Number.prototype.chr = function() {
return String.fromCharCode(this);
}
var n = 33;
console.log(n.chr());
http://jsfiddle.net/CXWeV/
Also, as Bryan points out, the following will work:
console.log((33).chr());
console.log(Number(33).chr());
But, the following does not work:
33.chr();
EDIT: Although, as Gumbo points out, this does:
33..chr();
As well as a check if the property already exists (see Erik's answer for another way to check):
if (!Number.prototype.chr) {
Number.prototype.chr = function() {
return String.fromCharCode(this);
}
}
if (!Number.prototype.hasOwnProperty('chr')) {
Number.prototype.chr = function() {
return String.fromCharCode(this);
};
}
To use this the number must be in a variable or wrapped in parentheses. Be aware that converting a scalar number to a Number object (called boxing) has an overhead. If you are doing the conversion repeatedly on the same value, you'll want to explicitly convert it to an object first with Number().
Note that simply doing String.fromCharCode might be easier or more clear in some situations.
The normal way, really. Note the importance of surrounding the number in parentheses (or storing it in a variable), as a dot would normally indicate a decimal point:
Number.prototype.chr = function () {
return String.fromCharCode(this);
}
alert((97).chr()); // alerts "a"
I'm not sure whether this works in all browsers, but I'm assuming it does.
Interactive Example

Categories

Resources