Breakdown of indexOf function - indexof

Can someone explain this solution to me? A friend helped me, but he just wrote it all out and didn't explain it. Now, I'm really confused :(
_.indexOf = function(array, target){
var result = -1;
_.each(array, function(item, index) {
if (item === target && result === -1) {
result = index;
}
});
return result;
};
return result;
};

The function traverses through all the elements of the array and returns index of the first element that is equal to target. The code could also look like this:
_.indexOf = function(array, target){
var result = -1;
_.each(array, function(item, index) {
if (item === target) {
result = index;
return false;
}
});
return result;
}

Related

Iterable Mapping- how to retreive all the values with For-Loop?

From looking at the code below can anyone show me how you'd write a for loop to get all the values in the mapping? Thanks in advance for the help.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract IterableMapping {
mapping(address => uint) public balances;
mapping(address => bool) public inserted;
address[] public keys;
function set(address _addr, uint _bal) external {
balances[_addr] = _bal;
if (!inserted[_addr]) {
inserted[_addr] = true;
keys.push(_addr);
}
}
function get(uint _index) external view returns (uint) {
address key = keys[_index];
return balances[key];
}
function first() external view returns (uint) {
return balances[keys[0]];
}
function last() external view returns (uint) {
return balances[keys[keys.length - 1]];
}
```
oh i see my mistake now with trying to get the bool values. it would be...
function getAllBools() public view returns (bool[] memory) {
bool[] memory result = new bool[](keys.length);
for (uint i = 0; i < keys.length; i++) {
result[i] = inserted[keys[i]];
}
return result;
}
You can loop through balances by using address as key , hereby you will get All the values in the balances Mapping.
function getAllBalances() public view returns (uint[] memory){
uint[] memory result = new uint[](keys.length);
for (uint i = 0; i < keys.length; i++) {
result[i] = balances[keys[i]];
}
return result;
}
Likewise you can also get values of the inserted mapping

Sort array of objects based on property in typescript

I'm showing an array with items of type 'request' in a table. I want to sort the columns of the table so I planned to make a click method for every column header. This methods sorts the array based on the value of the property shown in that column.
public sortProduct(): void {
this.requests.sort((a, b) => {
if (a.productName < b.productName)
return -1;
if (a.productName > b.productName)
return 1;
return 0;
});
if (!this.productSortOrder) {
this.requests.reverse();
this.productSortOrder = true;
} else {
this.productSortOrder = false;
}
}
This works, but now I need to make a method for every column. I am looking for a way to call a sort method like this:
this.requests.sortMethod(property, order);
This method would then sort the requests array based on the property of the objects in the array and in the given sortorder.
How can I do that? I guess I'm looking for something like Func<> in C#.
You can us a function signature for a similar effect to Func
sortProduct<T>(prop: (c: Product) => T, order: "ASC" | "DESC"): void {
this.requests.sort((a, b) => {
if (prop(a) < prop(b))
return -1;
if (prop(a) > prop(b))
return 1;
return 0;
});
if (order === "DESC") {
this.requests.reverse();
this.productSortOrder = true;
} else {
this.productSortOrder = false;
}
}
// Usage
sortProduct(p=> p.productName, "ASC");
Or you can use the property name instead (keyof Product will ensure the string must be a property of Product):
sortProduct<T>(propName: keyof Product, order: "ASC" | "DESC"): void {
this.requests.sort((a, b) => {
if (a[propName] < b[propName])
return -1;
if (a[propName] > b[propName])
return 1;
return 0;
});
...
}
// Usage
sortProduct("productName", "ASC");
sortProduct("productName_", "ASC"); // Error
You can use a SortUtil class with a static template method sortByProperty:
export class SortUtil {
static sortByProperty<T>(array: T[], propName: keyof T, order: 'ASC' | 'DESC'): void {
array.sort((a, b) => {
if (a[propName] < b[propName]) {
return -1;
}
if (a[propName] > b[propName]) {
return 1;
}
return 0;
});
if (order === 'DESC') {
array.reverse();
}
}
}

Java 8 Stream, anyMatch

boolean isSuccess = aMap.entrySet().stream().anyMatch(entry -> {
AKey aKey= entry.getKey();
BValue bValue = bMap.get(aKey);
if (bValue == null) {
return false;
}
AValue aValue = entry.getValue();
if (compareDetail(aValue, bValue)) {
return false;
}
return true;
}
);
this code always only loop one time, how can i loop all elements then return true when two if blocks false?
It seems you need to try allMatch instead.

Gwt CellTable Sorting page by page only

GWT CellTable column sorting page by page only, for each page i have to click the column header
for sorting.
How to sort whole data on single header click.
This is my code,
dataProvider = new ListDataProvider<List<NamePair>>();
dataProvider.addDataDisplay(dgrid);
List<List<NamePair>> list = dataProvider.getList();
for (List<NamePair> contact : test) {
dataProvider.setList(test);
list.add(contact);
}
ListHandler<List<NamePair>> columnSortHandler = new ListHandler<List<NamePair>>(dataProvider.getList());
System.out.println("Column count->"+dgrid.getColumnCount());
for(int j=0 ; j<dgrid.getColumnCount();j++){
final int val = j;
columnSortHandler.setComparator(dgrid.getColumn(val), new Comparator<List<NamePair>>() {
public int compare(List<NamePair> o1, List<NamePair> o2) {
if (o1 == o2) {
return 0;
}
// Compare the column.
if (o1 != null) {
int index = val;
return (o2 != null) ? o1.get(index-2).compareTo(o2.get(index-2)) : 1;
}
return -1;
}
});
}
dgrid.addColumnSortHandler(columnSortHandler);
I suggest you override ListHandler , override and call super.onColumnSort(ColumnSortEvent) to debug the onColumnSort(ColumnSortEvent) method, you'll understand what is happening very fast.
The source code of the method is pretty direct
public void onColumnSort(ColumnSortEvent event) {
// Get the sorted column.
Column<?, ?> column = event.getColumn();
if (column == null) {
return;
}
// Get the comparator.
final Comparator<T> comparator = comparators.get(column);
if (comparator == null) {
return;
}
// Sort using the comparator.
if (event.isSortAscending()) {
Collections.sort(list, comparator);
} else {
Collections.sort(list, new Comparator<T>() {
public int compare(T o1, T o2) {
return -comparator.compare(o1, o2);
}
});
}
}

socket.io variable check

Okay so basically I have a variable in ajax which I want to send to my socket.io server to check if the variable is already in a json array.
Ajax:
function isUniqueEmail(email) {
//email checking script here
$.get('info/mailcheck.js' + email, function(response) {
if(response == 1) {
alert("Your email is already on our list");
}
else {
alert("We will add you shortly");
};
})
};
the json array:
{"mail":
[
"tom#gmail.com",
"fred#gmail.com",
"bob#gmail.com"
]}
The socket.io part is where im confused. Basically it just needs to take the variable (an email) check if it is already in the array and return a 1 if it is or return a zero if not and write it in the array.
I don't know much about node.js but you could use a function a bit like the following to check if a value is in an array and push the value to it if it is not.
function pushToArray(value, array) {
function inArray(val, arr) {
for (var i=0; i<arr.length; i++) {
if (arr[i] == val) {
return true;
}
return false;
}
if (inArray(value, array) {
return 1;
} else {
array.push(value);
return 0;
}
}
Are you confused about how to get this to work with socket.io or just how to find the element in the array? If you're using node.js, just use the array.indexOf method:
//obj = {"mail": ["mail1#foo.com", "mail2#baz.com"]}
if (obj.mail.indexOf(email) != -1) {
//We have your email!
}
else {
//We don't
}

Resources