Re: unique index

2018-03-22 Thread Dippo
@mashigan & @miran Ty guys, you both point me to tables and i also thought that 
tables would solve my problem. I thought that tableref would reference the 
content like record number. But it reference the whole table. The point is that 
i want to prevent to walk through the whole table to see if a value exists. But 
i think that there is no other option.

But now i am thinking/talking about it, i suddenly have a idea what would solve 
this. Because i know what the key's are before compilation.

Thanks guys.


Re: unique index

2018-03-22 Thread miran
Maybe I'm misunderstanding the question, but to me this looks like a case where 
you would want to use [tables](https://nim-lang.org/docs/tables.html) instead 
of seq.


Re: unique index

2018-03-22 Thread mashingan
But maybe wrapped to `TableRef` is better I guess instead of seq if you need to 
have unique key


Re: unique index

2018-03-22 Thread mashingan
implement proc `==` and `contains` for you specialized type


import sequtils

type
DataBuffer* = tuple
  key : string
  mytype  : string
  value   : string

proc `==`(a, b: DataBuffer): bool =
  a.key == b.key


proc contains[T: DataBuffer](d: T, dbuf: seq[T]): bool =
  for data in dbuf:
  if d == data:
  return true
  false

# change proc to be different to work with generic add
proc dataAdd[T: DataBuffer](data: var seq[T], newdata: T): bool 
{.discardable.} =
  if newdata in data:
  data[data.find(newdata)] = newdata
  false
  else:
  data.add newdata
  true

var mydata = newSeq[DataBuffer]()

mydata.dataAdd(("a","int","4"))
mydata.dataAdd(("a","int","5"))

echo mydata # if expect only the last add to be visible ([a, int, 5])


With boolean return, you can know whether it replaced old value or add new to 
collections. You can just change the dataAdd to return DataBuffer so it will 
return old value that's be replaced or return a newly added value.