diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

How to use factories to create relationships which follow a sequence

Factories an extremely useful tool for testing. The more complex the use case, the more awesome you find out Laravel factories are.

For instance, we might need to create a few items, each one with a different measurement of its own:

 Item::factory()
    //...
    ->has(Measurement::factory()->state(new Sequence(
        ['length' => 50, "width" => 110],
        ['length' => 65, "width" => 200],
        ['length' => 190, "width" => 295],
    )))
  ->count(3)
  ->create()

This will result in 3 items, each item having one unique measurement assigned. The first item will have a measurement with values corresponding to the first array in the sequence and so on.

JavaScript reduce function performance enhancement

Time complexity of implemented algorithms is an aspect which for sure should be taken into consideration when working on websites with big amounts of data. In this manner, let us test out the performance of the mother and father of all JavaScripts higher order functions - Array.prototype.reduce.

Problem description: Our API provides us with an array of objects that looks something like:

const objects = [
   { id: 1, name: "name 1"},
   { id: 2, name: "name 2"},
   { id: 3, name: "name 3"},
]

and we want to create a lookup table out of it, like this:

{
   1: "name 1",
   2: "name 2",
   3: "name 3",
}

using reduce:

const lookup = objects.reduce((lookup, object) => ({
     ...lookup,
     [object.id]: object.name
}), {})

It works, but the time complexity of this algorithm is (unexpectedly) O(n^3), because of the internal calls of Object.assign() that needs to copy bigger and bigger objects from iteration to iteration.

This is what JavaScript does internally:

objects.reduce((lookup, object) => Object.assign(
            Object.assign(lookup, {}), 
            { [object.id]: object.name }
        ), 
    {}
);

Time taken:

    100 records: ~0.08ms
  1.000 records: ~1.45ms
 10.000 records: ~  18ms
100.000 records: ~2600ms
1 mill  records: ~breaks

Performance boost:

const lookup = objects.reduce((lookup, object) => {
    lookup[object.id] = object.name
    return lookup
}, {})

Time taken:

    100 records: ~0.045ms
  1.000 records: ~ 0.15ms
 10.000 records: ~  1.5ms
100.000 records: ~  3.2ms
1 mill  records: ~   20ms

Great performance improvement by avoiding Object.assign calls and new object creation in each iteration.

TypeScripts Writable Computed Refs

Writable Computed Refs can be of real help when using Vue's Composition API along with TypeScript. Let's see what they are and how we can use them by getting through an example.

Problem description: let's assume we have to display a dialog with all our online users, if there are any. At the same time, we have the option to disable dialogs on our website, for some reason. In order achieve our goals, we are using an UI library like PrimeVue, Ant or Vuetify. These assist us with a reusable Dialog component that is visible when a boolean allows it to do so, something like this:

<Dialog 
   v-model:visible="isDialogVisible"
>

The problem that we encounter is that of declaring our isDialogVisible reactive variable. What are the problems you may think.

  1. It should both take into consideration if we have something to display in our list (if we have users in our store - using a getter for that) AND if we are allowed to display dialogs on our website. So it cannot be a simple reactive reference.

  2. You may think: alright, it's not really a problem, that's what computed properties are for. They are reactive and build up a value based on one or more raw variables. So this should solve the problem:

const isModalVisible = computed(() => useStore().getters.getOnlineUsers.length > 0 && areModalsAllowed.value);

Theoretically that's right, but it does not really solve our specific problem, because our dialog must also be closed in 3 scenarios (that means our isDialogVisible variable should be set to false): a. when dialogs are disabled on the website b. when we click on of the dialog's close button c. when the getter returns an empty list of users

The problem is that computed properties are not overridable. Depending on how you do it you could get one of the following warnings that cause unexpected behaviour and make the application not respond to the users commands of closing the dialog:

[Vue warn]: Computed property was assigned to but it has no setter.
[Vue warn]: Write operation failed: computed value is readonly.

Of course, it's a bad idea to empty the users list in the store and make the dialogs disabled on the website when you click on the close button, or to disable the dialogs on the website when there are no users in the store, or... you got the idea.

Here's where our Writable Computed Refs come into play and help us gracefully solve our problem:

const isDialogVisible: WritableComputedRef<boolean> = computed({
      get: (): boolean => useStore().getters.getOnlineUsers.length > 0 && areModalsAllowed.value,
      set: (newValue: boolean): void => { areModalsAllowed.value = newValue }
    });

Explanation: We can specifically state the generic WritableComputedRef type and construct our isDialogVisible boolean by providing an object with specific get and set methods to computed().
Our set method will be automatically used by the Dialog component when having to close the dialog due to the "Disable dialogs" button's click event. But when one checks for its value, our provided get method will also take the getters value into consideration.

We can understand this as surrounding(proxying) our computed property with custom get and set methods while it stays reactive.

How to dynamically render components in "vue-infinite-loading" using relative heights

When working with an infinite loading library like "vue-infinite-loading" or "vue-infinite-scroll", instead of hardcoding the amount of components to be rendered per page, we might use a technique to estimate the right number, based on the height of the browser window and the height of the component.

We need to obtain both of those heights and then divide them to obtain the number we are looking for. First, we can obtain the height of the browser window by using the following command:

window.innerHeight

After that, in order to obtain the height of the components rendered in the infinite scroll window, we may use:

this.$refs.yourComponentRefHere.clientHeight

"clientHeight" will return the height of the component and now, we can divide the numbers obtained to get the render number. ( Note: as a safety measure, the number we get should be larger than the obtained number, therefore we need to add a number to it to be sure it will behave as desired).

By using this technique we can change the render number in a responsive manner and can avoid unnecessary requests in order to give the user a more performant user experience.

Note: We can also dynamically adjust the render number if the window size changes, by adding a watcher and the following event listener:

window.addEventListener('resize',onResize)

Where "onResize" is the action to re-calculate the render number.

How to extend interfaces declared in external libraries in Typescript

Typescript allows us to easily extend types by using module augumentation.

Let's take a look at one quick example - extending the React Material Ui Library Theme.

All we need to do is create a file ending in .d.ts at the root of our Typescript project - in this case I'll name it material-ui.d.ts:

import {
  Theme as MuiTheme,
} from '@mui/material/styles';

declare module '@mui/material/styles' {
  export interface Theme extends MuiTheme {
    customization?: Record<string, string>;
  }
}

How to fix filter: blur() performance issue in Safari

The filter: blur() property in css may come in handy in some situations, but you should know of a side effect it has in Safari (tested on version 15.1 as of this writing).

The issue is a nasty performance drop around the element on which the filter is used, making every other interaction extremely slow. And it happens in Safari only. In other browsers everything works well.

One solution I've found so far is to use transform: translate3d(0, 0, 0) along with filter on the same element, to force the browser use GPU acceleration for that particular element instead of the CPU.

filter: blur(200px);
transform: translate3d(0, 0, 0);

How to set default attribute values for Laravel models

The problem:

Given the following schema:

 Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->unsignedBigInteger('number_of_hits')->default(0);
      $table->string('title');
  });

We when we create a new post:

$post = new Post(["title" => "test"]);

we might expect the 'number_of_hits' to be 0, but it is null.

The solution:

To fix this, we can easily tell Laravel what default values we want for the model attributes:

class Post extends Model
{
   ...
   protected $attributes = [
        'number_of_hits' => 0,
    ];
}

How to declare path aliases in Typescript

Defining path aliases using webpack can save you a lot of headache when it comes to imports, but you must also let Typescript know about them.

Following my previous post on declaring path aliases using webpack, you can configure your tsconfig.json file to in order to be able to use those aliases in Typescript like so:

{
  ...
  "paths": {
    "@/*": ["./src/*"],
    "images/*": ["./assets/images/*"],
  },
  "include": [
    ...
  ],
}

Of course, all paths for defined aliases must be reachable by Typescript. You can check this post out if you are not sure how to do that.

Otherwise, we are going to get this error:

Cannot find module 'images/[your module]' or its corresponding type declarations.

How to import images in Typescript

Normally, when Typescript cannot find something we get this error:

Cannot find module [your module] or its corresponding type declarations ts(2307)

Now let's see how we can fix this, with a simple example. Given the following folder structure:

│── src
│   ├── resources
│   │   ├── ts
│   │   │   ├── **/*.ts
│   │   ├── images
│   │   │   ├── logo.svg
├── ...
├── tsconfig.json

In order to be able to achieve something like this:

import Logo from '[path]/images/logo.svg'

without any ** Typescript errors**, we need to follow these steps:

1.Make sure that the images folder is "reachable" by Typescript.

Adding this inside tsconfig.json will do the trick:

{
  "include": [
        ...
        "resources/**/*.ts",
   ],
}

A configuration like this one will not do:

{
  "include": [
      "resources/ts/**/*.ts",
   ],
}

Because images/ is not included in ts/ and we don't have any other folders declared, so Typescript can't "reach" it.

2.Let Typescript know about the .svg type in that folder.

In the root of the images folder create a file called index.d.ts:

...
├── resources
│   ├── ts
│   │   ├── **/*.ts
│   ├── images
│   │   ├── logo.svg
│   │   ├── index.d.ts
...

With the following contents:

declare module '*.svg' {
  const value: any;
  export = value;
}

Now you should be good to go.

Making only some state properties persistent inside a persistent Vuex module

Making data persistent in web applications is a common required feature. State management patterns and libraries like Vuex provide systems for storing data in the local storage for achieving the persistence of data, making the data survive over refresh and making it reusable without having to request the data again.

The local storage has a (configurable) memory limit. Overflowing can cause unwanted behaviour and make the app work unexpectedly. Vuex gives the opportunity to make only some of its modules persistent, which is great.

Step 1: We import the modules and group them together in our modules object:

import store as module1 from '../module1Location'
import store as module2 from '../module2Location'
import store as module3 from '../module3Location'

const modules = {
  module1,
  module2,
  module3,
};

Step 2: For choosing which modules should be persistent, we can use the vuex-persistedstate plugin. We have to define the plugins array that will be passed to the createStore method like this:

const plugins = [
  createPersistedState({
    storage: window.localStorage,
    key: 'yourkey',
    paths: [
      'module1',
      'module2',
      'module3',
    ],
  }),
];

Step 3: Having only some modules to be persistent is nice. But what if we need to only make some parts of a module persistent? What if one of our modules should have all its state properties persistent except for one, the one that causes the unwanted local storage overflow?

Lets pretend our module3 has a property named bigData that causes the overlow.

Solution: we can add the REDUCER FUNCTION to our payload for the createPersistedState() function. Here is how our plugins array should look like:

const plugins = [
  createPersistedState({
    reducer: (state: RootState) => {
      const { module3, ...restOfRootState } = state;
      const { bigData, ...restOfModule3State } = module3;
      return {
        ...restOfRootState,
        module3: { ...restOfModule3State },
      };
    },
    storage: window.localStorage,
    key: 'yourkey',
    paths: [
      'module1',
      'module2',
      'module3',
    ],
  }),
];

Explanation of the reducer function: The reducer function takes in a state and returns the new state that should be persisted. We can change the state that we receive initially to only contain the data that we wish. Lets see how we extract the problematic bigData out of our module.

  1. We get our RootState as a parameter. This is an object containing all our Vuex modules.
  2. We extract in a variable our problematic module3 out of this RootState object and keep all other (non-problematic) modules in another separate object using the rest operator.
  3. We extract our problematic bigData from our module3 variable (the one extracted at step2) and keep all other (non-problematic) state properties in another object using the rest operator.
  4. We return the new state object that we build by spreading out the object containing the non-problematic modules using the spread operator and by redefining our module3 that should now contain only the non-problematic state properties (all its previous properties except bigData).

Step 4: passing the modules and plugins objects to the createStore() function, through its payload.

export const store = createStore({
  modules,
  plugins,
});

After this, the local storage will only help persist our modules, without the module3's bigData object that was causing our local storage overflow.