Categories
Vue 3

Getting Started with Vue 3

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at how to create our first project with Vue 3.

Installation

We can install the Vue Devtools with by installing the browser extension according to the instructions at https://github.com/vuejs/vue-devtools#vue-devtools.

A standard Electron app is also available.

It can be used to debug our Vue apps.

To install the Vue package, we can run:

npm install vue@next

to install the NPM package.

Vue CLI is also available for create our Vue project.

We can run:

yarn global add @vue/cli@next

or

npm install -g @vue/cli@next

to install the Vue CLI globally.

Vite is a web dev build tool that lets us serve our code faster with the ES module import approach.

We can run:

$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev

or

$ yarn create vite-app <project-name>
$ cd <project-name>
$ yarn
$ yarn dev

to create a Vue app with Vite, install the packages, and run the app.

We can also include Vue 3 as script tag.

For instance, we can write:

<script src="https://unpkg.com/vue@next"></script>

to add the script tag.

Get Started

We can get started by creating our first Vue app.

To do that, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      {{ message }}
    </div>
    <script>
      const app = {
        data() {
          return {
            message: "hello world"
          };
        }
      };

      Vue.createApp(app).mount("#app");
    </script>
  </body>
</html>

to create a simple Vue app.

In the head tag, we add our Vue package.

We add our template in the div with ID app .

Then we create our app object with the data method to return our data.

We pass the object to the Vue.createApp method and call mount with a CSS selector to let us mount the app.

How we should see ‘hello world’ displayed on the screen.

This is because the text is interpolated from the data as indicated by the double curly braces.

In addition to interpolating text on the template, we can also use the v-bind attribute on the template to display the text.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div v-bind:title="message">{{message}}</div>
    </div>
    <script>
      const app = {
        data() {
          return {
            message: "hello world"
          };
        }
      };

      Vue.createApp(app).mount("#app");
    </script>
  </body>
</html>

The v-bind directive lets us set a dynamic value for an element’s attribute.

Now when we hover over the ‘hello world’ text, we should see the same thing displayed.

Handling User Input

We can use the v-on directive to handle user input.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <p>{{ state }}</p>
      <button v-on:click="toggle">toggle</button>
    </div>
    <script>
      const app = {
        data() {
          return {
            state: true
          };
        },
        methods: {
          toggle() {
            this.state = !this.state;
          }
        }
      };

      Vue.createApp(app).mount("#app");
    </script>
  </body>
</html>

We have the v-on:click directive to let us listen to clicks on an element.

The value we passed in as the value of the directive is the method we’ll call when we click on th button.

It refers to the toggle method to toggle this.state to the opposite value.

Now when we click the toggle button, we’ll see the state on the template toggle between true and false .

Conclusion

We can get started with Vue 3 with a script tag or a package.

Vue Devtools let us debug our Vue app easier.

Once we have the Vue framework package added, we can create simple apps with it.

v-on lets us listen to events and v-bind lets us set attributes.

Categories
JavaScript

Learning JavaScript by Implementing Lodash Methods — Objects

Lodash is a very useful utility library that lets us work with objects and arrays easily.

However, now that the JavaScript standard library is catching up to libraries such as Lodash, we can implement many of the functions in simple ways.

In this article, we’ll look at some Lodash object methods that we can implement ourselves in plain JavaScript.

forInRight

The forInRight method loops through the own and inherited properties of an object in reverse order. In each iteration, it calls the iteratee function with the value, key, and object arguments until it returns false . Then the loop will end.

value is the value of the object property that’s being looped through. key is the key of the property that’s being looped through, and object is the object where the properties are being traversed.

We can implement that ourselves by using the for...in loop to get all the keys in the order that it returns and put them in an array.

Then we can reverse the keys by calling the array instance’s reverse method and use the for...of loop to loop through the keys:

const forInRight = (object, iteratee) => {
  const keys = [];
  for (const key in object) {
    keys.push(key);
  }
  const reversedKeys = keys.reverse();
  for (const key of reversedKeys) {
    const result = iteratee(object[key], key, object);
    if (result === false) {
      break;
    }
  }
}

In the code above, we first used the for...in loop to loop through the keys of an object forward and put them all in the keys array.

In the for...in loop, we push the keys into the keys array. Then we reverse the keys that are in keys array by calling reverse and then assign the reversed array as the value of reversedKeys .

Then we can use the for...of loop to loop through reversedKeys and then call iteratee with object[key], key, and object . We assigned the returned value of iteratee to result .

When result is false , we break the loop.

Now when we call it with the Foo constructor as follows:

function Foo() {
  this.a = 1;
  this.b = 2;
}

Foo.prototype.c = 3;

forInRight(new Foo(), (value, key) => console.log(key));

We get that we get back c , b and a as the logged values in that order.

findKey

The Lodash findKey finds the first property of an object where the predicate returns true .

We can implement that by traversing the items of an object and call the predicate function to check if the given property value matches the condition returned by the predicate .

For instance, we can implement that as follows:

const findKey = (object, predicate) => {
  for (const key of Object.keys(object)) {
    if (predicate(object[key])) {
      return key
    }
  }
}

In the code above, we used Object.keys to get the own keys of object . Then we looped through the keys with the for...of loop.

Inside the loop, we call predicate with the value of the object to see if it meets the condition defined in the preicate function.

Then when we run the findKey function as follows:

const users = {
  'foo': {
    'age': 15,
    'active': true
  },
  'bar': {
    'age': 30,
    'active': false
  },
  'baz': {
    'age': 1,
    'active': true
  }
};

const result = findKey(users, o => o.age < 40);

We have the users object with multiple keys with an object with the age and active properties as the value.

Then we called findKey with it and the predicate function set to o => o.age < 40 .

We then get that 'foo' is the value of result .

Photo by Paweł Czerwiński on Unsplash

findLastKey

Lodash’s findLastKey function is like findKey except the keys are looped over in the opposite order of it.

To implement it, we can just change our findKey implement by calling the reverse method on the keys array returned by Object.keys .

We can do that as follows:

const findLastKey = (object, predicate) => {
  for (const key of Object.keys(object).reverse()) {
    if (predicate(object[key])) {
      return key
    }
  }
}

Then we call our findLastKey function as follows:

const users = {
  'foo': {
    'age': 15,
    'active': true
  },
  'bar': {
    'age': 30,
    'active': false
  },
  'baz': {
    'age': 1,
    'active': true
  }
};

const result = findLastKey(users, o => o.age < 40);

We get 'baz' as the value of result instead of 'foo' since we looped through the keys in reverse.

Conclusion

The forInRight method can be implemented by putting the own and inherited in an array by looping through them with the for...in loop and then pushing them in the array.

Then we can loop through them with the for...of loop and call the iteratee function on it.

The findKey and findKeyRight functions can be implemented by looping through the keys and then calling the predicate function on it.

Categories
JavaScript

Learning JavaScript by Implementing Lodash Methods — Unzipping Arrays and Excluding Items

Lodash is a very useful utility library that lets us work with objects and arrays easily.

However, now that the JavaScript standard library is catching up to libraries such as Lodash, we can implement many of the functions in simple ways.

In this article, we’ll look at how to implement array methods for excluding items and unzipping arrays.

unzip

unzip accepts an array of grouped elements and creates an array by regrouping the elements into their configuration before zipping them.

All we have to do to implement unzip is to loop through each of the arrays and rearrange them as follows:

const unzip = (zipped) => {
  let unzipped = zipped[0].map(z => []);
  for (let j = 0; j < unzipped.length; j++) {
    for (let i = 0; i < zipped.length; i++) {
      unzipped[j].push(zipped[i][j])
    }
  }
  return unzipped;
}

In the code above, we created a function that takes zipped arrays and inside the function, we mapped the first entry of zipped to a new array of arrays.

This is because the unzipped array should have arrays that are of the same size as each array entry in the zipped array.

Then we push the zipped entry in the given position into the unzipped array’s array entry.

For instance, if we call unzip with the following zipped array:

const result = unzip([
  ['a', 1, true],
  ['b', 2, false]
]);

Then unzip first maps the first zipped entry into a new array and set it to the unzipped variable.

Then the nested loop takes 'a' and then puts it into the first entry of the unzipped array. Then it pushes 'b' as the 2nd entry of the same array.

In the next iteration, it pushes 1 into the next unzipped array entry. Then it pushes 2.

The same process is done for the next iteration. Therefore, the unzipped array should be:

[
  [
    "a",
    "b"
  ],
  [
    1,
    2
  ],
  [
    true,
    false
  ]
]

unzipWith

unzipWith is like unzip , but we can pass in an iteratee function to choose how to regroup our array. The iteratee function takes 2 arguments and returns the one that’s the combination of the 2.

For instance, we can implement unzipWith as follows:

const unzipWith = (zipped, iteratee) => {
  let unzipped = zipped[0].map(z => []);
  for (let j = 0; j < unzipped.length; j++) {
    for (let i = 0; i < zipped.length; i++) {
      unzipped[j].push(zipped[i][j])
    }
  }
  return unzipped.map(arr => {
    return arr.reduce(iteratee);
  });
}

It’s almost the same as unzip except that we called reduce to combine the values with iteratee via the map method before returning the unzipped array.

Then when we call it as follows:

const result = unzipWith([
  [1, 10, 100],
  [2, 20, 200]
], (a, b) => a + b);

We get:

[
  3,
  30,
  300
]

for result .

without

The Lodashwithout method returns an array that excludes all the given values using the SameValueZero algorithm for comparison.

We can easily exclude items with our own without function as follows:

const without = (arr, values) => arr.filter(a => !values.includes(a))

In the code above, we called filter on arr and the leave the ones that aren’t in values by calling includes to check if it’s in values .

Then when we call it as follows:

const result = without([1, 2, 3, 4, 5], [4]);

We get that result is:

[
  1,
  2,
  3,
  5
]

xor

The xor function returns an array of unique values that aren’t included in all arrays. This is also known as the symmetric difference.

The order of the result is determined by when they occur in the array.

To implement it, we can just check whether they occur in all arrays and then exclude them if they do:

const xor = (...arrs) => {
  const symDiff = [];
  for (const arr of arrs) {
    for (const a of arr) {
      const inAllArrays = arrs.every(arr => arr.includes(a));
      if (!inAllArrays) {
        symDiff.push(a);
      }
    }
  }
  return symDiff;
}

In the code above, we looped through each array in arrs then inside, we loop through each array entry in each entry of arrs and check whether an element is in every array in arrs by using the every method on arrs .

The callback uses includes to check whether each element is in each array in arrs .

If it’s not, then we push it to the symDiff array, and in the end, we return that array.

Then when we call it as follows:

const result = xor([2, 1], [2, 3])

We get that result is:

[
  1,
  3
]

since 1 and 3 are not in all the arrays.

Conclusion

unzipping arrays means that we’re rearranging the entries so that each entry in the nested array is now in their own array position.

We can also return a new array with some entries excluded with the without function, which we can implement with filter and includes .

Finally, we can find the symmetric difference by checking if the elements are included in each array in the nested array and exclude those.

Categories
JavaScript

Learning JavaScript by Implementing Lodash Methods — Objects and Functions

Lodash is a very useful utility library that lets us work with objects and arrays easily.

However, now that the JavaScript standard library is catching up to libraries such as Lodash, we can implement many of the functions in simple ways.

In this article, we’ll look at some Lodash object and function methods that we can replace with our own plain JavaScript implementation.

unary

The Lodash unary method returns a function that only calls the original function with one argument.

We can just create our own function that returns a function that calls the original function ourselves as follows:

const unary = (fn) => (val) => fn(val);

In the code above, we have our own unary function, which takes a function that returns (val) => fn(val) , which is a function that only takes one argument and then calls fn with that argument.

Then we can call it as follows:

const result = ['6', '8', '10'].map(unary(parseInt));

And we get:

[
  6,
  8,
  10
]

as the value of result .

wrap

The Lodash wrap method takes a wrapper function another function fn that we want to call with the wrapper as the first argument.

It returns a function that takes in a value val as the parameter and calls the function in the second argument with the wrapper as the first argument and val as the 2nd argument.

For instance, we can implement our own wrap function as follows:

const wrap = (wrapper, fn) => (val) => fn(wrapper, val)

In the code above, the wrap function takes wrapper and fn , which are functions. Then we return a function that takes in an argument, which is val and then calls fn with wrapper and val .

Then we can call it as follows with the Lodash _.escape method as the first argument and our own function to wrap our text around p tags as follows:

const p = wrap(_.escape, (func, text) => `<p>${func(text)}</p>`);

In the code above, the escape method escapes the text and our own function wraps func(text) , where func is the escape method since that’s the first argument and text is the text that we’ll pass into the returned p function.

Then we can call p as follows:

const result = p('foo bar');

and we get that result is <p>foo bar</p> .

Photo by Rachel Hisko on Unsplash

forIn

The Lodash forIn method loops through the own and inherited enumerable string keyed properties of an object and run an iteratee function on each property.

The iteratee is a function that takes the value , key , and object parameters and we can stop the loop by returning false explicitly

We can implement our own forIn function as follows:

const forIn = (object, iteratee) => {
  for (const key in object) {
    const result = iteratee(object[key], key, object);
    if (result === false) {
      break;
    }
  }
}

In the code above, we have the forIn function that takes an object and an iteratee function.

Then inside the function, we used the for...in loop to loop through all the enumerable own and enumerable string keys of object .

Inside the loop, we call the iteratee function with the value, which we get by using object[key] , the key itself, and the object . We assign the return value of iteratee to result .

Then if result is false , then we break the loop. Otherwise, it continues running.

We can then call our forIn function as follows:

function Foo() {
  this.a = 1;
  this.b = 2;
}

Foo.prototype.c = 3;

forIn(new Foo(), (value, key) => console.log(key));

In the code above, we have the Foo constructor, which has 2 own properties a and b . It also has an additional inherited property c .

Then we called forIn with a Foo instance, and pass in a callback that logs the keys of the Foo instance.

In the end, we should see a , b and c logged in the console log output.

Conclusion

The unary and wrap Lodash methods both return a function that takes in some arguments and call the original function that’s passed in as the argument from the returned function.

Lodash’s forIn method is like the for...in loop, except that we can return false with our iteratee function to break the loop. The iteratee is run on every iteration until it returns false .

Categories
JavaScript

Useful Lodash Methods — Finding Uniques

Lodash is a utility library that has lots of methods for manipulating objects. It has stuff that we use all the time and also things that we don’t use frequently or don’t think of using.

In this article, we’ll look at how to use Lodash methods to create data structures with unique entries.

_.union([arrays])

The union method takes a comma-separated list of arrays and return an array with the unique entries from all the arrays combined. The results are chosen from the first array in which the value occurs.

For instance, we can use it as follows:

import * as _ from "lodash";

const arr = _.union([1, 2, 3], [2, 3, 4]);
console.log(arr);

Then arr is [1, 2, 3, 4] since we have 1, 2, 3, and 4 included as entries of one or both arrays.

.unionBy([arrays], [iteratee=.identity])

The unionBy method takes a list of arrays as the first arguments, and then a function that’s called as the values are being iterated through. The function determines what values are considered unique. The results are chosen from the first array in which the value occurs.

It returns a new array of combined values.

For instance, we can use it as follows:

import * as _ from "lodash";

const arr = _.unionBy([1, 2.1, 2.7, 3], [2.8, 3.1, 4], Math.round);
console.log(arr);

Then we get:

[1, 2.1, 2.7, 4]

as the value of arr since we called Math.round on each and then compare them to see which ones are the same after rounding with Math.round .

There’s also a shorthand to find the unique value by the property of the object. For example, we can write:

import * as _ from "lodash";

const arr = _.unionBy([{ x: 2 }], [{ x: 2 }, { x: 1 }], "x");
console.log(arr);

Then we get:

[
  {
    "x": 2
  },
  {
    "x": 1
  }
]

as the value of arr .

_.unionWith([arrays], [comparator])

We can use unionWith to takes one more array and a comparator function to compare the values each item and see which ones are equal. It takes the first one from the list of items that are considered the same.

Then it put those values in the array and returns it. For example, we can use it as follows:

import * as _ from "lodash";

const arr1 = [{ x: 1, y: 3 }, { x: 2, y: 1 }];
const arr2 = [{ x: 1, y: 1 }, { x: 1, y: 3 }];
const arr = _.unionWith(arr1, arr2, _.isEqual);

Then we write have:

[
  {
    "x": 1,
    "y": 3
  },
  {
    "x": 2,
    "y": 1
  },
  {
    "x": 1,
    "y": 1
  }
]

as the value of arr as it takes the first value that’s unique in the arrays and put them in the returned array.

Photo by Daniel McCarthy @themccarthy on Unsplash

_.uniq(array)

The uniq method takes an array and then returns a new array that has the duplicates eliminated.

For instance, we can use it as follows:

import * as _ from "lodash";

const arr = _.uniq([1, 2, 3, 4, 4, 5]);

Then we get:

[
  1,
  2,
  3,
  4,
  5
]

as the value of arr .

Conclusion

Lodash has methods to return arrays by getting unique values from one or more arrays and return them in a new array. Some also support different ways of determining if the value is unique by our criteria like the unionBy method.