To get better at functional programming in JavaScript, I started leaning Elm.
In JavaScript you have the object shorthand notation:
const foo = 'bar';
const baz = { foo }; // { foo: 'bar' };
I was wondering whether there is something like that in Elm? I'm asking because I have the following model:
type alias Model =
{ title : String
, description : String
, tag : String
, tags : List String
, notes : List Note
}
type alias Note =
{ title : String
, description : String
, tags : List String
}
And an update function that upon receiving the AddNote action adds the note to the notes array and clears the inputs:
AddNote ->
{ model | notes = model.notes ++ [ { title = model.title, description = model.description, tags = model.tags } ], title = "", description = "", tag = "" }
I know that in function definitions you can "destructure" records, but I think even in the return type I would have to explicitly type out each key of the record.
AddNote ->
{ model | notes = model.notes ++ [ getNote model ], title = "", description = "", tag = "" }
getNote : Model -> Note
getNote { title, description, tags } =
{ title = title, description = description, tags = tags }
There is not a shorthand record notation similar to JavaScript objects.
However, a type alias also serves as a constructor function, so you could have something like this:
getNote : Model -> Note
getNote { title, description, tags } =
Note title description tags
Related
I have a terraform variable:
variable "volumes" {
default = [
{
"name" : "mnt",
"value" : "/mnt/cvdupdate/"
},
{
"name" : "efs",
"value" : "/var"
},
]
}
and I am trying to create a dynamic block
dynamic "volume" {
for_each = var.volumes == "" ? [] : [true]
content {
name = volume["name"]
}
}
but I get an error when I run plan
name = volume["name"]
│
│ The given key does not identify an element in this collection value.
the desired output would be:
volume {
name = "mnt"
}
volume {
name = "efs"
}
what is wrong with my code?
Since you are using for_each, you should use value. Also you condition is incorrect. It all should be:
dynamic "volume" {
for_each = var.volumes == "" ? [] : var.volumes
content {
name = volume.value["name"]
}
}
As you are creating an if-else like condition to pass value to for loop, the condition needs a value to set. https://developer.hashicorp.com/terraform/language/meta-arguments/for_each
Need to replace [true] with var.volumes to pass the value.
for_each = var.volumes == "" ? [] : var.volumes
And, then set the value in the content block with .value to finally set the values to use.
content {
name = volume.value["name"]
The final working code is below as #marcin posted.
dynamic "volume" {
for_each = var.volumes == "" ? [] : var.volumes
content {
name = volume.value["name"]
}
}
You can simply use for_each = var.volumes[*]:
dynamic "volume" {
for_each = var.volumes[*]
content {
name = volume.value["name"]
}
}
or:
dynamic "volume" {
for_each = var.volumes[*]
content {
name = volume.value.name # <------
}
}
There is a table A and jsonb field 'context', it looks like:
{
"variable": {},
"other_stuff": {}
}
I need to add a new property to 'varialbe' every time i run query. So It should do smth like:
query1
{
"variable": {
"var1": "var1Value"
},
"other_stuff": {}
}
query2
{
"variable": {
"var1": "var1Value1",
"var2": "var1Value2"
},
"other_stuff": {}
}
And if variable already has this field, it should replace it.
I run this sql, and it works:
let sql = UPDATE chatbots.A SET context = context || jsonb_set(context, '{variable, var1}', 'var1Value1')
It works but when i need to replace 'var1' and 'var1Value1' by parameters ($1 and $2) - it doesn't work (in node-postgres)
I realized that i can replace second parameter by
to_jsonb($2::text)
But what should i do with the first one?
My javascript code
async setUsersVariables(params: {users: ChatUser[], variable_name: string, variable_value: string}) {
const {users, variable_name, variable_value} = params
if (!users.length) return false
let sql = "UPDATE chatbots.A SET context = context || jsonb_set(context, '{variable, $1}', to_jsonb($2)::text) WHERE chat_user_id IN ( "
const parsedUsers = users.map(e=> e?.chat_user_id)
let sqlParams: any[] = [variable_name, variable_value]
let idx = 3;
({ sql, idx, params: sqlParams } = addSqlArrayParams(sql, parsedUsers, idx, sqlParams));
sql += ` RETURNING chat_id, chat_user_id, platform, platform_user_id`;
const filteredUsers: any = (await this.pool.query(sql, sqlParams)).rows
return filteredUsers
}
i have the following type User:
type alias User =
{ id : Int
, name : String
, age : Maybe Int
, deleted : Bool
}
User is a type used in my Model:
type alias Model =
{ users : List User
, name : String
, age : String
, message : String
}
When I iterate over "List User" using List.map like this...
Delete id ->
let
newUserList =
List.map
(\user ->
if user.id == id then
{ user | deleted = True }
else
user
)
model.users
in
( { model | users = newUserList }, Cmd.none )
... the Compiler tells me:
The 2nd argument to function `map` is causing a mismatch.
List.map
(\user ->
if user.id == id then
{ user | deleted = True }
else
user
)
model.users
Function `map` is expecting the 2nd argument to be:
List { a | id : Int, name : String }
But it is:
List (Bool -> User)
That is pretty strange for me.
Why does my map function change the Type User...?
I do not change it, I just iterate over, map each user and if I found the right one, by its id, I change deleted value to True...
I am a bit confused...
Can anyone help?
kind regards :)
UPDATE: It does not seem to me a problem of the List.map function but of the type alias User declaration.
As soon as I add another value this breaks...
Here is the whole code for it. It is kept pretty simple.
Note: As soon as you uncomment the Users property "deleted" the compiler throws an error
module Main exposing (..)
import Html exposing (Html, text, h1, div, img, input, form, ul, li, i, hr, br)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Html.App as App
import String
import Random
--import Debug
--import Uuid
main : Program Never
main =
App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
--MODEL
type alias Model =
{ users : List User
, name : String
, age : String
, message : String
}
type alias User =
{ id : Int
, name : String
, age :
Maybe Int
-- , deleted : Bool
}
init : ( Model, Cmd Msg )
init =
( initModel, Cmd.none )
initModel : Model
initModel =
{ users = []
, name = ""
, age = ""
, message = ""
}
--UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
InsertName username ->
( { model | name = username }, Cmd.none )
InsertAge age ->
let
newAge =
case String.toInt age of
Err err ->
""
Ok value ->
toString value
newMessage =
case String.toInt age of
Err err ->
"Age must be a number!"
Ok int ->
""
in
( { model | age = newAge, message = newMessage }, Cmd.none )
InitNewUser ->
( model, Random.generate AddNewUser (Random.int 1 9999) )
AddNewUser randomId ->
if String.isEmpty model.name then
( { model | message = "Please give a name" }, Cmd.none )
else
let
ageAsInt =
case String.toInt model.age of
Err err ->
Nothing
Ok int ->
Just int
newUser =
User randomId model.name ageAsInt
newUserList =
newUser :: model.users
in
( { model | users = newUserList, name = "", age = "" }, Cmd.none )
Delete id ->
let
newUserList =
List.map
(\user ->
if user.id == id then
{ user | name = "--deleted--" }
else
user
)
model.users
in
( { model | users = newUserList }, Cmd.none )
--VIEW
type Msg
= InsertName String
| InsertAge String
| AddNewUser Int
| InitNewUser
| Delete Int
userListView : Model -> Html Msg
userListView model =
let
newList =
List.filter (\user -> (user.name /= "--deleted--")) model.users
in
newList
|> List.sortBy .name
|> List.map userView
|> ul []
userView : User -> Html Msg
userView user =
let
ageAsString =
case user.age of
Just val ->
val |> toString
Nothing ->
"-"
in
li []
[ div [] [ text ("ID: " ++ toString user.id) ]
, div [] [ text ("Name: " ++ user.name) ]
, div [] [ text ("Age: " ++ ageAsString) ]
, input [ type' "button", value "Delete", onClick (Delete user.id) ] []
]
view : Model -> Html Msg
view model =
div [ class "wrapper" ]
[ h1 [] [ text ("We have " ++ toString (List.length model.users) ++ " Users") ]
, Html.form []
[ input [ type' "text", onInput InsertName, placeholder "Name", value model.name ] []
, input [ type' "text", onInput InsertAge, placeholder "Age", value model.age ] []
, input [ type' "button", onClick InitNewUser, value "Add new user" ] []
]
, div [] [ text model.message ]
, userListView model
, hr [] []
, div [] [ text (toString model) ]
]
The problem is this part of the AddNewUser message:
newUser =
User randomId model.name ageAsInt
It is missing False as the forth argument when you use the deleted property.
If you do not include it, the User function will return a partially applied function that still needs a Bool to return a proper user. The compiler seems to get thrown off by this even though all your types and functions have proper annotations.
Another way that leads to a better error message would be to define newUser like this:
newUser =
{ id = randomId
, name = model.name
, age = ageAsInt
, deleted = False
}
I have this model
type alias Model =
{ exampleId : Int
, groupOfExamples : GroupExamples
}
type alias GroupExamples =
{ groupId : Int
, results : List String
}
In my update function, if I want to update the exampleId would be like this:
{ model | exampleId = updatedValue }
But what if I need to do to update, for example, just the results value inside of GroupExamples?
The only way to do it in the language without anything extra is to destructure the outer record like:
let
examples = model.groupOfExamples
newExamples = { examples | results = [ "whatever" ] }
in
{ model | groupOfExamples = newExamples }
There is also the focus package which would allow you to:
set ( groupOfExamples => results ) [ "whatever" ] model
I have a question regarding node orm2 hasMany association, my model definition is like this.
schemas/Channel.js
var model = db.define('channels', Channel, ChannelOptions);
var Channel = {
channel_name : String,
channel_email : String,
channel_id : String,
views : Number
};
var ChannelOptions = {
id : "channel_id",
methods: {
my_details : function (err) {
return this.channel_id +' '+ this.channel_name + ' ' + this.views;
}
}
};
schemas/network.js
var model = db.define('networks', Network, NetworkOptions);
var Channel = require('../schemas/Channel')(db);
model.hasMany('channels', Channel, {}, {autoFetch:true});
model.sync()
db.sync(function(){
console.log('DB SYNCHED');
});
var Network = {
network_id : Number,
name : String,
username : String,
logo : String,
website : String
};
var NetworkOptions = {
id : "network_id",
methods: {
}
};
It created a networks_channels table and I have filled it with a networkID and channelID. it is responding with the property (channels) but it is empty.
Is there something missing?
Just figured out what was wrong.
Its becauset I have set up the database table definitions before doing db.sync(). Turns out that its doing all the work for me. Clearing up the tables and refilling it with data did the trick.