js fuction to compare 2 items for equality - algorithm

Trying to create a function that would compare 2 items based on equality. Unfortunately, it doesn't work properly please help.
//This is what I have so far:
function checkEquality(a,b){
if (a===b) {
return "The type and values are equal."
}else if (a==b && typeof a !== typeof b) {
return "The type is different."
}else if (a!==b){
return "The value and type are different."
}
}
console.log(checkEquality(1,true))
console.log(checkEquality(0,"0"))
console.log(checkEquality(1,1))

Related

QT - Wrong numbering in the case of two or more overlapping numberings

I need to use two nested lists.
The first is a numeric list and the second is an alphabetical one.
When the second is over and I go to the first list, the numbers are counted from the beginning.
I tried to create a new list createList() but it didn't work
else if (object == ui->textEdit_left && event->type() == QEvent::KeyPress)
{
QTextCursor cursor = ui->textEdit_left->textCursor();
QTextListFormat::Style currentStyle = cursor.currentList()->format().style();
QTextBlockFormat format = cursor.blockFormat();
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
QTextListFormat::Style newStyle = createNewStyle(currentStyle, keyEvent->key());
if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)
{
format.setIndent(format.indent() - 1);
cursor.setBlockFormat(format);
cursor.createList(newStyle);
return true;
}
else if (keyEvent->key() == Qt::Key_Tab)
{
format.setIndent(format.indent() + 1);
cursor.setBlockFormat(format);
cursor.createList(newStyle);
return true;
}
else
{
return false;
}
}
return false;

Order an array of objects by the value of their enums in swift

I have an array of CLBeacon objects which all have a property .proximity.
I want to order the array by this property which contains the CLProximity enum. So I want all objects to be in order IMMEDIATE, NEAR, FAR, UNKNOWN.
Is there a way to do this neatly without resorting to a bunch of if statements?
If you define a (computed read-only) property sortIndex of CLProximity
extension CLProximity {
var sortIndex : Int {
switch self {
case .Immediate:
return 0
case .Near:
return 1
case .Far:
return 2
case .Unknown:
return 3
}
}
}
then you can sort an array of beacons with
let sortedBeacons = sorted(beacons) { $0.proximity.sortIndex < $1.proximity.sortIndex }
If .Unknown is the only CLProximity value that needs
"special treatment" and all other possible values are in the desired
relative order then you can simplify the property definition to
extension CLProximity {
var sortIndex : Int {
return self == .Unknown ? Int.max : rawValue
}
}
You can use custom comparator and sort an array using that ,
You will "say" for all objects that has "unknown" proximity are "bigger" than others
var sortedArray = persons.sortedArrayUsingComparator {
(obj1, obj2) -> NSComparisonResult in
if obj1.proximity.rawValue == obj12.proximity.rawValue {
return NSComparisonResult.OrderedSame
} else if obj1.proximity == .UNKNOWN || obj1.proximity.rawValue > obj12.proximity.rawValue {
return NSComparisonResult.OrderedDescending
}
return NSComparisonResult.OrderedAscending
}
Based on what Julia wrote above I had cobbled this together:
self.beacons = beacons as! [CLBeacon]
var tempBeacons = zip(self.beacons, self.beacons.map({
(b: CLBeacon) -> Int in
if b.proximity == .Immediate {
return 0
} else if b.proximity == .Near {
return 1
} else if b.proximity == .Far {
return 2
} else if b.proximity == .Unknown {
return 3
}
return 0
}))
self.beacons = sorted(tempBeacons, {$0.1 < $1.1}).map({ $0.0 })
Thanks all!
Based on #Martin answer.
You can also create Int enum and assign value to it and then sort it like below.
enum myEnum: Int {
case A = 0
case B = 1
case C = 2
case D = 3
}
let myData : [myEnum:[String]] = [.C:["3"],.D:["4"],.B:["2"],.A:["1"]]
print(myData.first?.key)
let newData = myData.sorted(by: { $0.key.rawValue < $1.key.rawValue })
print(newData.first?.key)
Hope this helps
Swift 5
Now you can just add Comparable to your enum and it respects the order
enum ContainerLevel: Comparable {
case empty
case almostEmpty
case halfFull
case almostFull
case full
}
//Are we running low?
let needMoreCoffee = coffeeMugLevel > .halfFull
print(needMoreCoffee) //true
Link to more Code examples

New row in slickgrid, Validator does not fire

I have the requiredFieldValidator configured for one of my columns and it works as expected for existing rows. When I tab thru, or click to begin editing a new row, the validator does not fire when moving off the column. When move off the new row (with no data in the column) so that it commits, and then move back to the row, now the validator works...but ONLY if I put some data in the editor, and then delete it.
In other words, for new rows, the requiredFieldValidator does not do anything until I actually type something in the column. If I leave a column blank it never fires, defeating the purpose of it. Interestingly, the example they provide (http://mleibman.github.com/SlickGrid/examples/example3-editing.html) exhibits the same problem.
This checks for both values being "". I believe this should return true since a validator could be a "required" validator.
this.isValueChanged = function () {
// this needs to validate if both are empty since a validator might be a "required" validator
if ($input.val() == "" && defaultValue == "")
return true;
else
return (!($input.val() == "" && defaultValue == "")) && ($input.val() != defaultValue);
};
Preferred method would be to create a custom editor so you aren't mucking with the core library.
I concur, just encountered this behavior myself.
Here is the solution.
Change this.isValueChanged function contents to the following.
if(($input.val().length > 0) && ($input.val() != defaultValue))
return true;
else if(($input.val() == defaultValue)&&($input.val().length > 0))
return true;
else if(($input.val().length == 0) && ((undefined === defaultValue )||(defaultValue == "")))
return true;
else
return false;
For some reason defaultValue is not set during the first interraction, my guess if you initialize it to "" you would not need to check for undefined.
At any rate defaultValue holds the previous value of the cell, so when it is empty and it is the first cell being edited it is undefined, after that it is set to "" for all other empty cells.
The problem is this function needs to tell the grid that the value has changed in order for the cell editor to validate the input. In the provided implementation the expression always returns false because
$input.val() == "" evaluates to true and then the expression
!($input.val() == "" && defaultValue == null)) evaluates to false
This means defaultValue is continuously undefined.
Hope that makes sense and my code helps you out.
Had the same problem and I believe that ideally defaultValue should be set to undefined or null, when it wasn't initialized. So I've modified TextEditor in a following way:
function TextEditor(args) {
var $input;
var defaultValue;
var scope = this;
this.loadValue = function (item) {
defaultValue = item[args.column.field] || null;
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.isValueChanged = function () {
return $input.val() != defaultValue;
};
....
setting default defaultValue to null and simplifying isValueChanged.
There is an error in the first else if of Roman, the return is false. Otherwise, any change in cell returns true even if the value has not been changed.
I tried this and it works.
this.isValueChanged = function () {
var attuale = $input.val();
if((attuale.length > 0) && (attuale != defaultValue))
return true;
else if((attuale == defaultValue)&&(attuale.length > 0))
return false;
else if((attuale.length == 0) && ((undefined === defaultValue )||(defaultValue == "")))
return true;
else
return false;
};

LINQ distinct selection based on a property value

I have a generic list of countries completely filled with countries instances.
List <Country> mylist
This list has different instances of countries but some has the same value for the property "name".
How could i make a distinct over the property of the country "name" to get only the countries with different names?
Thanks.
Greets.
Jose.
Jon suggested MoreLINQ, which is obviously fine, but maybe you want to avoid another dependency. In this case, you can use Enumerable.Distinct with your own IEqualtyComparer<Country>:
var distinctCountries = myList.Distinct(new EqualityComparerForCountryByName());
//IEqualityComparer
class EqualityComparerForCountryByName : IEqualityComparer<Country> {
public bool Equals(Country x, Country y) {
if(Object.ReferenceEquals(x, y)) { return true; }
if(x == null || y == null) { return false; }
return x.Name == y.Name;
}
public int GetHashCode(Country obj) {
if(obj == null) { return 0; }
return obj.Name.GetHashCode();
}
}
You could use MoreLINQ with its DistinctBy method:
var distinctCountries = allCountries.DistinctBy(c => c.Name);
(You don't have to take all of MoreLINQ of course - you could just copy that one method into your code along with the ThrowIfNull extension method, and preserve the licence text appropriately.)

Axapta Validation Override Always Executes Twice

In most cases, validation methods I've overridden execute twice each time the parent field is changed. Everything still works, but the InfoLog displays double messages every time.
Is there any way to prevent this?
Thanks
public boolean validate()
{
boolean ret;
int exlowValue;
int lowValue;
int highValue;
int exhighValue;
str errorMessage;
;
ret = super();
//Make sure a numeric value was entered
if (ABC_RegExValidator::validateMe("integer", int2str (ABC_Checks_checkExtremeLow.value())))
{
//get the form values
exlowValue = ABC_Checks_checkExtremeLow.value();
lowValue = str2int(ABC_Checks_checkLow.valueStr());
highValue = str2int(ABC_Checks_checkHigh.valueStr());
exhighValue = str2int(ABC_Checks_checkExtremeHigh.valueStr());
//Extreme Low must be 0 or less than all others
if (exlowValue != 0)
{
//A non-zero value was entered; it must be less than all other fields
if ((exlowValue >= lowValue && lowValue > 0) || (exlowValue >= highValue && highValue > 0) || (exlowValue >= exhighValue && exhighValue > 0))
{
//Return an error
ret = checkfailed(strFmt("#ABC197", int2str(exlowValue)));
}
else
{
//Not greater than any other value
//Success!
ret = true;
} //Greater than all others?
}
else
{
//No errors
ret = true;
} // 0?
}
else
{
//Regular expression failed
//Return an error
ret = checkfailed("#ABC192");
} //Regular expression
return ret;
}
Your description of the problem is not really clear. One can override the valite method on a form control, the validate method on a form datasource and the validatefield method on the table. That's my knowledge of version 3.0.
And how do you mean the "parent field"? I presume the table field?
If I put info messages in each of these methods they only execute once when I modify a value. That's the case in 3.0. I don't know which version you're using.
Maybe you could be more precise about which validation method you're testing?

Resources