This code in typescript:
const b
if (a == true) {
b = [1]
} else {
b = [2]
}
how to convert above code to immutable.js ?
You have two options:
let b
if (a) {
b = List([1])
} else {
b = List([2])
}
//or
const b = a ? List([1]) : List([2])
Related
I made a program in JavaFX with Kotlin I managed to make a CSV and TXT reading separated by ";" where I have efficiency problems and I don't know how I could improve the efficiency to make the SQL query construction.
fun generatedDelimited(filePath: String, table: String = "") {
val sourceFile = File(filePath)
var line: String?
var header: Array<String>? = null
val lines: MutableList<List<String>> = ArrayList()
try {
BufferedReader(FileReader(sourceFile)).use { br ->
header = br.readLine().split(";").toTypedArray();
while (br.readLine().also { line = it } != null) {
val values : Array<String> = line!!.split(";").toTypedArray();
lines.add(Arrays.asList(*values))
}
}
} catch (e: IOException) {
e.printStackTrace()
}
val joined = "INSERT INTO $table (${header!!.joinToString(separator = ",")})\n"
var textSelect = "${joined}SELECT * FROM ( \n"
var selectUnion = ""
var lineNo = 1
for (line in lines) {
var columnNo = 0
var comma = ", "
var select = "SELECT "
var union = "UNION ALL\n"
if (lines.size.equals(lineNo)) {
union = ""
}
for (value in line) {
if (columnNo == 1) {
select = ""
}
if (line.size.equals(columnNo+1)) {
comma = " FROM DUAL \n$union"
}
selectUnion += "$select'$value' as ${header!![columnNo]}$comma"
columnNo++
}
lineNo++
}
textSelect += "$selectUnion);"
querySQL.text = textSelect
}
Result:
INSERT INTO werwsf (DATA1,DATA2,DATA3,DATA4,DATA5)
SELECT * FROM (
SELECT 'HOLA1' as DATA1, 'HAKA2' as DATA2, 'HAD3' as DATA3, '' as DATA4, 'ASDAD5' as DATA5 FROM DUAL
UNION ALL
SELECT 'HOLA6' as DATA1, 'HAKA7' as DATA2, 'HAD8' as DATA3, 'FA9' as DATA4, 'ASDAD10' as DATA5 FROM DUAL
);
Is there a way to improve efficiency? With 1600 rows it takes 5 minutes
Thank you.
this should be an optimised version of your code:
I used kotlin standard joinToString functions, which uses StringBuilder under the hood like #0009laH advised. I also removed the redundant list <-> array conversions and replaced the splitting and then joining back the first line (header) by the replace function, because it has the same effect as in the original code and it is faster. All these changes should result in faster, more readable and more concise code
fun generatedDelimited(filePath: String, table: String = "") {
val sourceFile = File(filePath)
val fileLines: List<String> = sourceFile.readLines()
val header: String = fileLines.first().replace(';', ',')
val lines: List<List<String>> = fileLines.drop(1).map { line ->
line.split(";")
}
val selectUnion = lines.joinToString(separator = "UNION ALL\n") { line ->
line.withIndex().joinToString(separator = ", ", prefix = "SELECT", postfix = " FROM DUAL\n") { (columnNo, value) ->
"'$value' as ${header[columnNo]}"
}
}
querySQL.text = "INSERT INTO $table ($header)\nSELECT * FROM ( \n$selectUnion);"
}
Here some complication sorting in my application.
Now i have data object is like following(called pCList):
Object[0]:
Id: 1
comp: Test
med: xyz
condition: valueObject.Condition
Object[1]:
Id: 2
comp: Test1
med: pqr
condition: valueObject.Condition
Object[2]:
Id: 3
comp: Test
med: abc
condition: valueObject.Condition
condition VO Have data like:
condition data1:
conId: 001
cond: abcds
condition data2:
conId: 001
cond: trdfd
condition data3:
conId: 001
cond: dsdsds
For normal sorting i will do as following way;
var sort:ISort = new Sort();
var sortField:ISortField = new SortField("med");
sort.fields = [sortField];
if(pCList != null)
{
pCList.sort = sort;
pCList.refresh();
}
In which pcList is sort by med.
But now, I want to sort by condition.cond
like first come which have cond value abcds then dsdsds then trdfd and so on...
I Have tried it using:
var sort:ISort = new Sort();
var sortField:ISortField = new SortField("condition.cond");
sort.fields = [sortField];
But not succeed. Any help is greatly appreciated.
ISort has a property compareFunction, that can be used for custom sorting. See example below.
var sort:ISort = new Sort();
sort.compareFunction = function(a:Object, b:Object, fields:Array = null):int {
var conditionA:String = a.Condition.cond;
var conditionB:String = b.Condition.cond;
if (conditionA < conditionB) {
return -1;
} else if (conditionA > conditionB) {
return 1;
} else {
return 0;
}
};
How is it possible to use inputs from the function and joins in slick
example
def query (coffeID : int) = DBAction { implicit rs =>
val implicitInnerJoin = for {
c <- coffees
s <- suppliers if ((c.supID === s.id ) && (c.cofID === coffeeID))
} yield (c.name, s.name)
-- edit typo with ====
you need to use ===
def query (coffeID : int) = DBAction { implicit rs =>
val query = for {
c <- coffees
s <- suppliers if (c.supID === s.id) && (c.cofID === coffeeID)
} yield (c.name, s.name)
query.list
}
here is my query:
List<string> kwList = GetFilterKeywords(); // returns NULL none keyword selected
var res = from d in ctx.Books
where (kwList == null || kwList.Contains(d.Name))
select d;
Looks like it is not legit to add where clause if kwList is NULL. So my question is: Is there any way to add more where clauses to the same query in IF/ELSE IF construction?
I mean:
var res = from d in ctx.Books
select d;
if (kwList != null)
{
res.Where(d => kwList.Contains(d.Name);
}
var res = ctx.Books; // no need to write select
if (kwList != null)
res = res.Where(x => kwList.Contains(x.Name));
foreach (d in res) {
...
}
You can use the tertiary operator
var res = kwList == null ? ctx.Books : ctx.Books.Where(x => kwList.Contains(x.Name));
If you want to modify the initial linq query in subsequent case statements, make sure to reassign the initial query to the modified:
var res = ctx.Books;
if (a == b)
{
// reassign here
res = res.Where(x => kwList.Contains(x.Name));
}
else if (a == c)
res = res.Where(x => x.Id == y);
How can I return a function side-effecting lexical closure1 in Scala?
For instance, I was looking at this code sample in Go:
...
// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return b
}
}
...
println(f(), f(), f(), f(), f())
prints
1 2 3 5 8
And I can't figure out how to write the same in Scala.
1. Corrected after Apocalisp comment
Slightly shorter, you don't need the return.
def fib() = {
var a = 0
var b = 1
() => {
val t = a;
a = b
b = t + b
b
}
}
Gah! Mutable variables?!
val fib: Stream[Int] =
1 #:: 1 #:: (fib zip fib.tail map Function.tupled(_+_))
You can return a literal function that gets the nth fib, for example:
val fibAt: Int => Int = fib drop _ head
EDIT: Since you asked for the functional way of "getting a different value each time you call f", here's how you would do that. This uses Scalaz's State monad:
import scalaz._
import Scalaz._
def uncons[A](s: Stream[A]) = (s.tail, s.head)
val f = state(uncons[Int])
The value f is a state transition function. Given a stream, it will return its head, and "mutate" the stream on the side by taking its tail. Note that f is totally oblivious to fib. Here's a REPL session illustrating how this works:
scala> (for { _ <- f; _ <- f; _ <- f; _ <- f; x <- f } yield x)
res29: scalaz.State[scala.collection.immutable.Stream[Int],Int] = scalaz.States$$anon$1#d53513
scala> (for { _ <- f; _ <- f; _ <- f; x <- f } yield x)
res30: scalaz.State[scala.collection.immutable.Stream[Int],Int] = scalaz.States$$anon$1#1ad0ff8
scala> res29 ! fib
res31: Int = 5
scala> res30 ! fib
res32: Int = 3
Clearly, the value you get out depends on the number of times you call f. But this is all purely functional and therefore modular and composable. For example, we can pass any nonempty Stream, not just fib.
So you see, you can have effects without side-effects.
While we're sharing cool implementations of the fibonacci function that are only tangentially related to the question, here's a memoized version:
val fib: Int => BigInt = {
def fibRec(f: Int => BigInt)(n: Int): BigInt = {
if (n == 0) 1
else if (n == 1) 1
else (f(n-1) + f(n-2))
}
Memoize.Y(fibRec)
}
It uses the memoizing fixed-point combinator implemented as an answer to this question: In Scala 2.8, what type to use to store an in-memory mutable data table?
Incidentally, the implementation of the combinator suggests a slightly more explicit technique for implementing your function side-effecting lexical closure:
def fib(): () => Int = {
var a = 0
var b = 1
def f(): Int = {
val t = a;
a = b
b = t + b
b
}
f
}
Got it!! after some trial and error:
def fib() : () => Int = {
var a = 0
var b = 1
return (()=>{
val t = a;
a = b
b = t + b
b
})
}
Testing:
val f = fib()
println(f(),f(),f(),f())
1 2 3 5 8
You don't need a temp var when using a tuple:
def fib() = {
var t = (1,-1)
() => {
t = (t._1 + t._2, t._1)
t._1
}
}
But in real life you should use Apocalisp's solution.