How to save operators in Dart - flutter

I want to do something like this in dart.
var z = +
and then put it in another var like this
var x = 5 z 5
And when I did this
var z = +
I get an Error
Expected an identifier.

you can not make variable operators in dart though what you can do is to create a custom variable for the same by doing:
void main() {
var operators = {
'+': (a, b) { return a + b; },
'<': (a, b) { return a < b; },
// ...
};
var op = '+';
var x = operators[op]!(10, 20);
print(x);
}

Related

split the string into equal parts flutter

There is a string with random numbers and letters. I need to divide this string into 5 parts. And get List. How to do it? Thanks.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
Should work:
List<String> list = [
'05b37ffe',
'4973959c',
'4d4f2d5c',
'a0c14357',
'49f8cc66',
];
I know there'a already a working answer but I had already started this so here's a different solution.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
List<String> list = [];
final divisionIndex = str.length ~/ 5;
for (int i = 0; i < str.length; i++) {
if (i % divisionIndex == 0) {
final tempString = str.substring(i, i + divisionIndex);
list.add(tempString);
}
}
log(list.toString()); // [05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d=1
; try{
d = (str.length/5).toInt();
print(d);
}catch(e){
d=1;
}
List datas=[];
for(int i=0;i<d;i++){
var c=i+1;
try {
datas.add(str.substring(i * d, d*c));
} catch (e) {
print(e);
}
}
print(datas);
}
OR
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d = (str.length / 5).toInt();
var data = List.generate(d - 3, (i) => (d * (i + 1)) <= str.length ? str.substring(i * d, d * (i + 1)) : "");
print(data);//[05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
If you're into one liners, with dynamic parts.
Make sure to import dart:math for min function.
This is modular, i.e. you can pass whichever number of parts you want (default 5). If you string is 3 char long, and you want 5 parts, then it'll return 3 parts with 1 char in each.
List<String> splitIntoEqualParts(String str, [int parts = 5]) {
int _parts = min(str.length, parts);
int _sublength = (str.length / _parts).ceil();
return Iterable<int>
//Initialize empty list
.generate(_parts)
.toList()
// Apply the access logic
.map((index) => str.substring(_sublength * index, min(_sublength * index + _sublength, str.length)))
.toList();
}
You can then use it such as print(splitIntoEqualParts('05b37ffe4973959c4d4f2d5ca0c1435749f8cc66', 5));
splitWithCount(String string,int splitCount)
{
var array = [];
for(var i =0 ;i<=(string.length-splitCount);i+=splitCount)
{
var start = i;
var temp = string.substring(start,start+splitCount);
array.add(temp);
}
print(array);
}

Render lit / lit-html TemplateResult as string

In lit/lit-html/lit-element, a standard component is the TemplateResult (usually HTMLTemplateResult), created like:
function renderMe(msg) {
return html`<div>Hello ${msg}!</div>`;
}
and of course the power and efficiency of the library is that subsequent calls will reuse the same <div> Element and only replace the changed fragments.
For testing the renderMe() function above, however, it would be helpful to be able to see the return value as a standard string, like:
assert.equal(RENDER_AS_STRING(renderMe('kimiko')), '<div>Hello kimiko!</div>');
and fix any bugs in the function before testing how it renders into the browser itself.
Is there a function like RENDER_AS_STRING either in lit itself or in a testing library? I have searched and not found one.
The result of execution contains html strings and values that alternate:
We can combine them in the same order:
function renderMe(msg) {
return html`<div>Hello ${msg}!</div>`;
}
const getRenderString = (data) => {
const {strings, values} = data;
const v = [...values, ''] // + last emtpty part
return strings.reduce((acc,s, i) => acc + s + v[i], '')
}
console.log(getRenderString(renderMe('SO')))
You can test it in the playground
And the recursive version
import {html, css, LitElement} from 'lit';
function renderMe(msg) {
return html`<p>Hello ${msg}!</p>`;
}
function renderBlock(msg) {
return html`<div>${renderMe(msg)}</div>`;
}
const getRenderString = (data) => {
const {strings, values} = data;
const v = [...values, ''].map(e => typeof e === 'object' ? getRenderString(e) : e )
return strings.reduce((acc,s, i) => acc + s + v[i], '')
}
document.getElementById('output').textContent = getRenderString(renderBlock('SO'))
#Daniil Loban's answer works great if the arguments are strings, but if they might themselves be TemplateResults or arrays of TemplateResults (which are all allowed by spec), it needs a more complex answer:
export function template_as_string(data) {
const {strings, values} = data;
const value_list = [...values, '']; // + last empty part
let output = '';
for (let i = 0; i < strings.length; i++) {
let v = value_list[i];
if (v._$litType$ !== undefined) {
v = template_as_string(v); // embedded Template
} else if (v instanceof Array) {
// array of strings or templates.
let new_v = '';
for (const inner_v of [...v]) {
new_v += template_as_string(inner_v);
}
v = new_v;
}
output += strings[i] + v;
}
return output;
}

Why am I getting an error while trying to run this on dart?

the operator '+' can't be unconditionally invoked because the receiver can be null.
var numbers = <int>[1,3,2,5,4];
var initialValue = 10;
void main() {
var foldNum = numbers.fold(initialValue, (curr, next) => (curr + next));
print(foldNum);
}
Specify the type of fold as fold<int>...
var numbers = <int>[1,3,2,5,4];
var initialValue = 10;
void main() {
var foldNum = numbers.fold<int>(initialValue, (curr, next) => (curr + next));
print(foldNum);
}

Dart split integer and add their values

Suppose I have a variable int a = 12345, I want to split a to [1,2,3,4,5] and add them like [1+2+3+4+5] and in final I want to get a result of a = 15 how can I achieve this?
All u have to do is recursively add every digit individually.
void main() {
int a = 12345;
int sum = 0;
while(a>0){
sum = sum + (a%10);
a = (a/10).floor();
}
print(sum);
//if u want to store in a
a = sum;
}
There are different ways to achieve the same, one of the ways is as:
void main() {
int num = 12345;
int sum = 0;
String numAsString = num.toString();
for (int i = 0; i < numAsString.length; i++) {
sum += int.parse(numAsString[i]);
}
print(sum); // 15
}
You can achieve using the split() as
void main(){
var i=34567;
var iStr=i.toString().split('');
var exp= iStr.join('+');
var sum=iStr.fold(0,(a,b)=>int.parse(a.toString())+int.parse(b));
print(exp);
print(sum);
}
Output:
3+4+5+6+7
25
If you need only the sum of the integer then
void main() {
var i = 34567;
var iStr = i.toString().split('');
var sum = iStr.fold(0, (a, b) => int.parse(a.toString()) + int.parse(b));
print(sum);
}
I would approach it by first converting the integer to a String.
Then mapping each single character into an int and finally simply
reduce the iterator of ints into the sum.
int num = 12345;
print(num
.toString()
.split('')
.map(
(c) =>int.parse(c)
).reduce((a,b) => a+b));

Trying to move e2e code into a function with no success

The problem is due to promise resolution, I pass in an xPath for all elements to be searched along with a string to search for and I would like the element returned. Here is the code:
export class Library {
static findListItem(xPath: string, findItem: string): any {
let z = 0;
const allItemsXPath = xPath.split('[X]');
const itemXPath = xPath.split('X');
console.log(xPath + ' : ' + findItem);
const itemList = element.all(by.xpath(allItemsXPath[0] + allItemsXPath[1])).map(function (item) {
return item.getText();
});
itemList.then(function (itemText) {
console.log(itemText.length);
for (let k = 0; k < itemText.length; k++) {
itemFound = true;
console.log(itemText[k] + ' : ' + findItem);
if (itemText[k] === findItem) {
z = k + 1;
console.log('found ' + z);
}
}
}).then(() => {
console.log(itemXPath[0] + z + itemXPath[1]);
// element(by.xpath(itemXPath[0] + z + itemXPath[1])).click();
return element(by.xpath(itemXPath[0] + z + itemXPath[1]));
});
};
The commented line for clicking works. It can see the element and click on it. I would like to return the element to the caller who would then click.
If the return isn't in a .then section then the return happens too quickly and z = 0. The way it is now, nothing is returned.
Your function findListItem no return value, Add return before itemList.then
static findListItem(xPath: string, findItem: string): any {
...
return itemList.then(function (itemText) {
...
});
}
Library.findListItem(xxx, yyy).then(function(item){
return item.click();
})
I have a question on your below code which to find the matched item, you compare one char of itemText with a whole string findItem per iterate. Are you sure you can find the matched one with below code.
for (let k = 0; k < itemText.length; k++) {
itemFound = true;
console.log(itemText[k] + ' : ' + findItem);
if (itemText[k] === findItem) {
z = k + 1;
console.log('found ' + z);
}
}