Author's Posts

css

Introduction

CSS ( Cascading Style Sheets ) is a language that allows you to describe the styles your markup should have. For a long time, I took CSS for a very simple thing that turns your text to a certain color, adds a little border here, maybe a cute animation here.

Then, I started to meet developers who were really good at CSS, and well, it’s a lot more than that… So, I’m spending some time becoming better at it, and we start with the basics.

Selectors

We could style our markup by adding a style attribute to each element:

<p style="color:red;">Paragraph</p>
<span style="color: red; font-size=14px;">Span element</span>

I let you imagine how many different rules you would have to write this way… let alone apply any kind of changes…

In CSS, we can use differents selectors. They allow us to group different elements and apply the same style rules to this group. We will explore:

  • Element selectors
  • Class and ID selectors
  • Attribute selectors

Element selectors

For markup, I will use HTML throughout this article. We can group our styles by elements. Give each *

* element a certain style for example.

The h1 and p tags are grouped and share the same rules. Instead of creating three different rules to style the paragraphs and two rules for my headers, I only make one for each.

You can also group different elements together by separating them with commas in CSS:

Do not forget the commas in this case! If you do, it won’t group the elements, but select the descendents elements.

Class and ID selectors

Classes

To allow more flexibility while selecting your elements, you can specify one or more classes to an element. Each class is space-separated. We use the class attribute.

<p class="danger"></p>
<h1 class="danger title"></h1>

In CSS, you use a period ( . ) to indicate that you are targetting a specific class name. You can chain several classes one after another.

.danger {
 /* Will style the paragraph */
}

.danger.title{
 /* Will style the h1*/
}

Note that the order is not important. If you specify .title.danger, the effect will be the same. It also doesn’t need to be an exact match. If you add a third class to your header, it will still follow the rules in the .danger.title block.

ID

ID are very similar to classes. The main differences are that an ID can only be used for one element. An element can only have one ID, because ID can’t have space-separated values. ID have more weight than classes. If you have an element with an ID and a class that change the same thing ( the color for example ), the style describe in the ID rules. Finally, ID are targetted by a pound sign ( # ) in a CSS declaration.

Attribute selectors

Class and ID are special attributes that CSS is able to handle in a special way. But in our markup, there are a LOT more attributes we can use. CSS allows us to target those in different ways to suit your needs

  • Simple attribute selector

You write CSS rules to check if an element has a special attribute specified. We don’t even care about the value. For example, I want to target all p element who have a key attribute:

p[key] {
  color: red;
}

/* OR, all elements with a key attribute, not just p */
[key]{
  color: red;
}

As you can see, we use [] in CSS to target attributes. So this is the first one, very general.

  • Exact attribute values

This time, we are looking for the exact attribute value.

  /* If the href is https://google.com, it won't match */
  a[href="google.com"] {
    color: purple;
  }

  /* The following are NOT equal */
  [class="danger warning"] {
    color: red;
  }

  .danger.warning {
    color: orange;
  }

Again, we are looking for an exact match. So, if we use the bracket notation, the element needs to have the classes danger and warning, in this order AND only those two. Quite different from the dot notation…

  • Partial attribute values

Finally, if you really want to have great control over the attributes you are using, you’ll need to use the following attribute selectors.

[attribute~="val"]{
  /* Attribute contains val in a space-separated list of words */
  /* Would match "friend" in "my friend Joe" */
}

[attribute*="val"] {
  /* Select any element with an attribute whose value CONTAINS val */
}

[attribute^="val"] {
  /* Select any element with an attribute whose value BEGINS with val */
}

[attribute$="val"] {
  /* Select any element with an attribute whose value ENDS with val*/
}

[attribute|="val"]{
  /* 
  Select any element with an attribute whose value starts with val followed by a dash (val-) 
  OR whose value is exactly equal to val.
  */
}

[attribute="val"i] {
  /* Add a i after the value to make it case insensitive ( The value will be case insensitive, NOT the attribute name. */
}

Examples:

Conclusion

There you have it. A quick overview of the different ways you can select elements with CSS. There are of course a lot of different things possible with these tools. But it should give you enough to play around.

Read more

Introduction

In the last few weeks, I was very intrigued by React native. I kept seeing more and more articles like this one, so I decided to take a deeper dive into React Native and actually use it, for real.

Meteor is the framework I use at work, and I now have some experience with it. I thought about connecting the React Native application with a Meteor back-end. This article will show you how to get things started.

Creating the Meteor app

First things first, we will create a Meteor application.

meteor create serverMeteor

For now, that is all we need. We’ll come back to that.

Creating our React Native app

I’ll use the very useful create-react-native-app tool. You can get more info on this, check this link. It will also explain how to use the Expo client app to see your work, very useful!

So, we run a command like this:

create-react-native-app reactFront

Now, you’ll have two folders. One named meteorServer that contains your Meteor application, and an other named reactFront where you will find your react-native application.

React-Native: Creating a simple PhoneBook

For the sake of brevity, we will create something simple. The user will have a form with two inputs. The first will take a name, the second a phone number.

After modifications, here is how App.js looks like:

import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';

export default class App extends React.Component {
  constructor(){
    super()
    this.state = {
      name: '',
      number: ''
    }
  }

  addPhoneNumber = () => {
    console.log(this.state)
    this.setState({
      number: '',
      name: ''
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          value={this.state.name}/>
        <TextInput
          style={styles.input}
          keyboardType='numeric'
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}
          value={this.state.number}/>

        <Button
          onPress={this.addPhoneNumber}
          title='Save Phone Number'/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    marginTop: 20
  },
  input: {
    borderWidth: 2,
    borderColor: 'gray',
    height: 50,
    margin: 10
  }
});

I added two TextInput elements and a Button element. I also added some styles for the input. In React Native, we use StyleSheet.create({}) to control styles. Or you could style use the inline objects as in React.

On my iOS simulator it looks like this:

Ok, for now, when we click ( or tap ) on the button. Nothing happens. It logs the values in the console and reset them. Let’s move on to the back-end.

Meteor: Preparing the method and publication

Go to the folder where your Meteor application is located. Mine was called serverMeteor.

Let’s create a /imports folder, and inside this /imports, we’ll add an /api folder. Just to follow the proper Meteor conventions.

Here is the plan: we will create a Meteor method that our React Native app will call when we click on the Save Phone Number button. This method will save the name and the number to the Meteor mongo database.

Then, we will create a publication that our React Native application will subscribe to. It will simply return all the entries we have. Let’s go!

In /imports/api/, let’s create a PhoneNumbers.js file that will hold our small back-end logic.

export const PhoneNumbers = new Mongo.Collection( 'phoneNumbers' )

Meteor.methods({
  addPhoneNumber( data ){
    PhoneNumbers.insert({
      name: data.name,
      number: data.number
    }, err => {
      if (err){
        return err
      } else {
        return null
      }
    })
  }
})

Meteor.publish( 'getAllNumbers', () => {
  return PhoneNumbers.find({})
})

Nothing fancy here. We create our collection, our method addPhoneNumber and our publication getAllNumbers. And that’s it for Meteor. Let’s make the two applications talk to one another.

React Native: Adding react-native-meteor

Go back to the React Native folder. We will use the react-native-meteor package to connect both applications.

npm install --save react-native-meteor

Here are the changes we need to make:

  • Call the addPhoneNumber method when we click our button.
  • Subscribe to our getAllNumbers publication
  • Display the numbers in a list
  • Make sure our React Native app is aware of our Meteor application.

Let’s start with the method call. If you’ve work with Meteor/React before, this will look very familiar:

// In our App component
addPhoneNumber = () => {
    const data = {
      number: this.state.number,
      name: this.state.name
    }

    Meteor.call('addPhoneNumber', data, err => {
      if( err ){
        console.log( err )
      } else {
        this.setState({
          number: '',
          name: ''
        })
      }
    })
  }

Next, let’s subscribe to our publication. For this, we will wrap our App component in createContainer provided by react-native-meteor. Let’s import it at the top of our file:

import Meteor, { createContainer } from 'react-native-meteor'

Good, now we will NOT export our App component, but the createContainer wrapper. Like so:

// The App Component will be defined above like so:
// class App extends React.Component{ ... } 

export default createContainer( () => {
  Meteor.subscribe('getAllNumbers')
  return {
    phoneNumbers: Meteor.collection('phoneNumbers').find({})
  }
}, App) // Need to specify which component we are wrapping

Ok, that’s done. So we will get the phone numbers in a nice array. We will display them in a list. Nothing fancy, we will use the FlatList component. Don’t forget to import FlatList from react-native. Our render function will look like so:

// Still in the App component my friend
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          value={this.state.name}/>
        <TextInput
          style={styles.input}
          keyboardType='numeric'
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}
          value={this.state.number}/>

        <Button
          onPress={this.addPhoneNumber}
          title='Save Phone Number'/>

        <FlatList
          data={this.props.phoneNumbers}
          keyExtractor={(item, index) => item._id}
          renderItem={({item}) => (
            <View>
              <Text>{item.name} || {item.number}</Text>
            </View>
          )} />
      </View>
    );
  }

FlatList takes the array of data and loops through it in the renderItem function. I’m just displaying the name and the phone number. keyExtractor is used to create keys for each element we render in this list, just like React needs in the web. Each key will be the ObjectID returned from MongoDB.

Finally, let’s make sure our React Native application knows where to get those informations:

//I have only one component anyway...
  componentWillMount(){
    Meteor.connect('ws://localhost:3000/websocket')
  }

We use the connect method from react-native-meteor.

Note: Because I am only using the iOS simulator here, I can use localhost. If you use the android simulator, you will need to use the IP address of your machine ( 192.168.xx.xx:3000/websocket for example).

Clicking on the Save Phone Number button will populate the database in our Meteor application. Our subscription to the publication will retrieve the informations and display them!

Just a final picture to show you how it looks on my iOS simulator:

Well, there you have it. You can now connect a React Native application to a Meteor application without a problem. Have fun!

Warning: It seems that using npm5 with create-react-native-app is buggy and doesn’t work properly. You should probably use npm4 or yarn to make sure you don’t encounter any problems for now.

Read more

meteor logo

Introduction

Meteor has become the go-to Javascript framework for our team. We use it in combination with React on the front-end. I thought I would write a quick tutorial to get started with Meteor + React. In addition, I’ll also touch on FlowRouter for the routing. If you do not have Meteor installed yet, you can follow the instructions from this page
Continue reading Meteor, React and FlowRouter: Quick Setup

Read more

crazy homer simpson

Introduction

This is just a little article to share a problem I encountered. I was tasked with building a CRM and transactions had to be filtered by date. Nothing fancy about all this. You check if the transaction’s date is between two other dates the user gives you ( a start date and an end one ).

The code

Well, here is how the code looked before I managed to solve it. I was using React with this code. I used the popular javascript library moment.js to work with dates.


renderTransactions(){
    return this.props.transactions.filter( transaction => {
        const start = moment(this.state.startDate)
        const end = moment(this.state.endDate)
        const tDate = moment(transaction.date)

        return tDate.isBetween(start, end) // Compare dates here
    })
    .map( ( transaction, i ) => {
        transaction.date = moment(transaction.date).format('DD/MM/YYYY')
        return (
            
                {transaction.amount}
                {transaction.date}
                {transaction.client}
            
    })
}

// etc.. etc...

Ok, can you see where the problem is? The first time the component renders, everything is fine, the dates are properly filtered. But, as soon as I modify the dates, nothing works anymore…

The problem was here:

transaction.date = moment(transaction.date).format('DD/MM/YYYY')

See how stupid that is? I mutate the state of my array with this line. On the next render, the date field is not longer a Date object that the moment library can work with, but a String…

Solving it, and restoring my sanity…

Take one:

Don’t use this.props directly. If I used a reference to this.props.transactions in my function, the problem wouldn’t have happened. Every time the function would run, a fresh copy of this.props.transactions would be used. Even if I kept the problematic line with the direct mutation, it would work.

Take two:

Immutability. Don’t mutate the state of your application directly. This line would have solved everything:

const date = moment(transaction.date).format('DD/MM/YYYY')

Done… Problem solved.

Conclusion

I’m just writing this to make sure I don’t make the same stupid mistake again. I spent way to much time on this… I’m tired and I hate programming.

Read more

Introduction

Aaaaah, prototypes… How many blog posts did you read where prototypes are listed as a must-know caracteristic of the language? How many times senior developers told you about prototypal inheritance? I’ve spent quite some time avoiding to learn more deeply about this thing. I got tired of procrastinating, so I wrote this thing.

Continue reading No, not inheritance, please call me delegation…

Read more

With ES6, we were given a new tool: generators. In a normal function, there is only one entry point: the invocation of the function itself. A generator allows you to pause the execution of a function and resume it later. Generators are useful when dealing with iterators and can simplify the asynchronous nature of Javascript.

Syntax

So, how would we define a generator, compared to a normal function? You declare a generator function by using the * ( asterisk ) operator after the function keyword:

function* awesomeGenerator(){
  //code
}

To pause the execution inside the generator, we use the statement yield:

function* awesomeGenerator(){
  yield 'Hey friend' // We pause the execution here
  console.log('Back again') // When we resume, we are here
}

next() method

A generator gives you a next() method, which is used to start/resume the execution. This method returns an object with two keys:

{
  value: [ yielded value ],
  done: [ true if we reach the end]
}

Let’s see a very simple generator in action:

function* groceriesGenerator(){
  yield 'Eggs'
  yield 'Tomatoes'
  yield 'Milk'
  return 'Paper Bag'
}

const groceries = groceriesGenerator()

console.log(groceries.next()) // [1]
console.log(groceries.next()) // [2]
console.log(groceries.next()) // [3]
console.log(groceries.next()) // [4]

// [1] { value: 'Eggs', done: false }
// [2] { value: 'Tomatoes', done: false }
// [3] { value: 'Milk', done: false }
// [4] { value: 'Paper Bag', done: true }

At our first groceries.next() call, our groceriesGenerator reached our first yield statement and paused, returning the value Eggs to the caller. Our second next() resumed the execution at the second yield statement, pausing it again and returning Tomatoes

Our last next() terminates the generator, returns Paper Bag and sets done to true.

As iterators

In the introduction, I said that generators could help to implement iterators. Let’s see an example:

function* iterationGenerator( arr ){
  for( let i = 0; i < arr.length; i++ ){
    yield arr[i]
  }
}

const iterator = iterationGenerator( ['John', 'Sarah', 'Joe', 'Emily'])

let current = iterator.next()

while( !current.done ){
  console.log( current.value )
  current = iterator.next()
}

// John
// Sarah
// Joe
// Emily

In this example, you can see how the state of the generator is maintained accross invocations. Whne we resume the execution by calling next(), the variables and loops are the same.

Pass values back to generators

Finally, you can also pass a value back to a generator. Here is a example:

function* twoWayGenerator(arr){
  for( let i = 0; i < arr.length; i++ ) {
    const symbol = yield 
    console.log(`${arr[i]} ${symbol}`)
  }
}

const prices = twoWayGenerator([10, 23, 12])

prices.next()
prices.next('€')
prices.next('£')
prices.next('$')

// 10 €
// 23 £
// 12 $

Here, our first next() will not print anything because we pause the execution before the first console.log. The second next() is called with an argument. This argument is provided as the returned value of the yield statement. We store this value inside the symbol variable and use it next.

You can also force a generator to throw an error:

prices.next()
prices.throw( new Error('Invalid Amount'))

//  const symbol = yield
//                   ^
//  Error: Invalid Amount

That’s it for a quick and dirty introduction about generators. In the next article, we will go a bit deeper and explore how generators can help us control the asynchronous flow of Javascript.

Read more

Introduction

Insert another intro about functional programming…

Composition

Composition is about creating small functions and creating bigger and more complete functions with them. Think of a function as a brick, composition is how you would make those bricks work together to build a wall or a house.

You might have encoutered composition in mathematics, written like so: f(g(x)). The function f is composed with the function g of x. Or f after g equals f of g of x. After because we evaluate the functions from right to left, from the inside to the outside:

f <-- g <-- x

The output of the precedent function becomes the input of the next. x is the input of g. The output of g(x) becomes the f input.

Examples?

Ok, let’s code something then. Imagine that you are a company that is in charge of manipulating text. You receive a bunch of words, and your customers want it back in a certain way.

A client comes at you with a text and says:

I want the words shorter than 5 characters to be uppercased.

We create three functions to execute those actions. One function takes the text and return words in lowercase. The second function look for short words and upperCase them. Finally, the third recreates the text from the array received.

function words( text ){
  return String( text )
    .toLowerCase()
    .split(/\s/)
}

function shortUpper( words ){
  return words.map( word => {
    if( word.length < 5 ){
      return word.toUpperCase()
    } else {
      return word
    }
  })
}

function createText( array ){
  return array.join(' ')
}

The client sends in the text and we make our functions work:

const text = 'Hello! My name is Damien and I love Javascript. Make this exciting.'

const allWords = words(text)
const upperText = shortUpper( allWords )
const newText = createText( upperText )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

Great! The client got what he wanted. The problem is: our workers have to manually take the output of the words and shortUpper functions, carry them to the next function, and turn on the function’s engine on. That’s a lot of work, can we automate this?

Cue dramatic music

Enter composition

We want the function’s outputs to be sent to the next function without having to do it ourselves. Like so:

const newText = createText( shortUpper( words( text ) ) )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

We read this from left to right, but, as I mentioned earlier, we execute from the inside to the outside:

createText <-- shortUpper <-- words <-- text

We even decide to create a function for this popular demand:

function upperLessThan5( text ){
  return createText( shortUpper( words( text) ) )
}

upperLessThan5( text )
//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

Our company has another popular demand: replacing ‘.’ by ‘!!!’ while making the first character of each word uppercase. We have some functions to handle that:

function exclamationMarks( words ){
  return words.map( word => word.replace('.', '!!!'))
}

function upperFirstChar( words ){
  return words.map( word => {
    return `${word[0].toUpperCase()}${word.substr(1)}`
  })
}

function firstCharUpperExclamation( text ){
  return createText( exclamationMarks( upperFirstChar( words( text ) ) ) )
}

firstCharUpperExclamation( text )
//Hello! My Name Is Damien And I Love Javascript!!! Make This Exciting!!!

Cool, we’re able to compose functions by combining several smaller functions!

Going nuts!

The company’s CEO couldn’t be happier. The factory transforms text very fast thanks to composing. But he wants more!

What if we had a function that took all the functions as inputs and just made composition happened by itself? We could call it compose.

The engineers gather up and brainstorm. They decide to experiment with the two products they already have. They come up with this:

function composeThreeFunctions(fn3, fn2, fn1){
  return function composed( firstValue ){
    return fn3( fn2( fn1( firstValue ) ) )
  }
}

function composeFourFunctions(fn4, fn3, fn2, fn1){
  return function composed( firstValue ){
    return fn4( fn3( fn2( fn1( firstValue ) ) ) )
  }
}

const upperLessThan5 = composeThreeFunctions( createText, shortUpper, words )
upperLessThan5( text )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

const exclamationFirstCharUpper = composeFourFunctions( createText, upperFirstChar, exclamationMarks, words)

exclamationFirstCharUpper( text )

//Hello! My Name Is Damien And I Love Javascript!!! Make This Exciting!!!

Our functions takes all the functions needed as parameters. It returns a function that takes the original value as parameters and return all the functions composed in the proper order. Be careful about the order! We execute from the inside to the outside. The last function you specified will be the first executed. How do the function remembers all the functions from the original function? Closure baby!

Now, we can compose whatever we want with three or four functions. But the CEO wants something generic.

What if we need to compose only two functions? or five? ten? I don’t want an infinite amount of functions sitting in my factory. Can you create one function that just take an arbitrary number of functions and compose?

Finally, the engineers come up with the compose function:

function compose( ...fns ){
  return function composed( value ) {
    let listOfFunctions = fns.slice()
    while( listOfFunctions.length > 0 ){
      value = listOfFunctions.pop()( value )
    }

    return value
  }
}

const upperLessThan5 = compose( createText, shortUpper, words )
upperLessThan5( text )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

const exclamationFirstCharUpper = compose( createText, upperFirstChar, exclamationMarks, words )
exclamationFirstCharUpper( text )

//Hello! My Name Is Damien And I Love Javascript!!! Make This Exciting!!!

The compose function takes a list of functions as a parameter. We use the rest operator (…) to gather that as an array. We return a function with the original value as parameter. Inside of this function, we create a local copy of the functions array ( how? CLOSUUUUUURE ). Then we call the last function of the array with the output of the last function. pop() returns the last element of the array and remove it from the array. The output of the last listOfFunctions element becomes the input of the next one. When our array is empty, we return the final value.

I mean, this is just amazing. Now we can go absolutely crazy.

Moar examples!!!

I’m just playing around now. But the sky is the limit.

const upperLessThan5Exclamation = compose( createText, shortUpper, exclamationMarks, words )
// OOOOOORRRR
const exclamationUpperLessThan5 = compose( createText, exclamationMarks, shortUpper, words )

// Same thing, different order

upperLessThan5Exclamation( text )
exclamationUpperLessThan5( text )
//hello! MY NAME IS damien AND I LOVE javascript!!! MAKE THIS exciting!!!
//hello! MY NAME IS damien AND I LOVE javascript!!! MAKE THIS exciting!!!

function replaceAbyE( words ){
  return words.map( word => {
    return word.replace(/a/gi, 'e')
  })
}

function replaceJavascriptWithPython( words ){
  return words.map( word => {
    if( word == /javascript/i ){
      return 'Python'
    } else {
      return word
    }
  })
}

const everything = compose( createText, shortUpper, exclamationMarks, upperFirstChar, replaceAbyE, replaceJavascriptWithPython, words )

everything( text )
//Hello! MY NEME IS Demien END I LOVE Python MEKE THIS Exciting!!!

Well, I’ll stop there. I want to see how librairies like Ramda implement composition, but this is really a fun way to write code.

Read more

Curry

Introduction

Well, time to teach myself something I don’t understand again…
In this article, we will explore a technique called currying. Currying is another concept in functional programming. It goes as follow: when a function expects several arguments, we break it down into successive chained functions that each take a single argument.

We reduce the arity of each function to one ( arity is the arguments length of a function ). Let’s see some examples.
Continue reading Explaining currying to myself

Read more