Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Grouping 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 Lodash methods that deal with grouping items in a collection.

keyBy

They keyBy method groups collection entries into keys as returned by a function that takes an entry as the parameter and returns the key according to what’s in the function’s code.

We can create our own keyBy function as follows:

const keyBy = (arr, fn) => {
  let obj = {};
  for (const a of arr) {
    obj[fn(a)] = a;
  }
  return obj;
}

In the code above, we just created an empty object, then populated it by calling fn with the array entry from the for...of loop and use it as the key.

Then the corresponding array entry is set as the value, and the object is returned.

When we call it as follows:

const arr = [{
    'dir': 'left',
    'code': 99
  },
  {
    'dir': 'right',
    'code': 100
  }
];
const result = keyBy(arr, o => String.fromCharCode(o.code))

Then result is:

{
  "c": {
    "dir": "left",
    "code": 99
  },
  "d": {
    "dir": "right",
    "code": 100
  }
}{
  "c": {
    "dir": "left",
    "code": 99
  },
  "d": {
    "dir": "right",
    "code": 100
  }
}

map

The map method returns an array that is mapped from the original array by calling a function on each entry and putting it in the new array.

Since the plain JavaScript has a map method for array instances, we can just use it to implement the Lodash map method.

Lodash’s map method also takes an object as an argument, which takes the keys and then maps the values with a function and put the values in the returned array.

We can implement this as follows:

const map = (collection, iteratee) => {
  if (Array.isArray(collection)){
    return collection.map(iteratee);
  }
  else {
    return Object.values(collection).map(iteratee)
  }
}

In the code above, we use the Array.isArray method to check if collection is an array. If it is, then we just use the array’s map method and use iteratee as the callback.

Otherwise, we use Object.values to return an array of object values and call map with iteratee as the callback on it.

Then we can call it as follows:

const result = map([4, 8], x => x**2);

which sets result to:

[
  16,
  64
]

Also, when we run:

const result = map({ 'a': 4, 'b': 8 }, x => x**2);

We get the same result.

partition

The partition method returns an array that’s grouped by the key returned by the function that’s passed in.

It groups an array by the key that’s returned by the function.

We can implement it as follows:

const partition = (collection, predicate) => {
  let obj = {};
  for (const a of collection) {
    if (!Array.isArray(obj[predicate(a)])) {
      obj[predicate(a)] = [];
    }
    obj[predicate(a)].push(a);
  }
  return Object.keys(obj).map(k => obj[k])
}

In the code above, we created an obj object, and then we loop through the collection with a for...of loop.

Then we create an array on with the key of obj that’s created by calling predicate on an entry.

If it’s not an array, then we set it to an empty array. Then we push the items according to the keys.

Finally, we return the values in an array by mapping the keys to the corresponding values.

Then when we call it as follows:

const users = [{
    'user': 'foo',
    'active': false
  },
  {
    'user': 'bar',
    'active': true
  },
  {
    'user': 'baz',
    'active': false
  }
];

const result = partition(users, o => o.active);

We get that result is:

[
  [
    {
      "user": "foo",
      "active": false
    },
    {
      "user": "baz",
      "active": false
    }
  ],
  [
    {
      "user": "bar",
      "active": true
    }
  ]
]

Conclusion

The keyBy method can be implemented by grouping the collections into an object with the for...of loop and populating the keys by calling the iteratee function. Then the values are populated by the corresponding key.

The map method can be implemented by the array instance’s map method.

partition can also be implemented by looping through all the objects and then populating the keys by calling the predicate with the array entry, and then we push the items into the array with the corresponding key.

Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — 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 how to implement some Lodash methods for converting functions to different forms.

bind

The Lodash bind function returns a function with a value of this that we set and with some arguments partially applied.

We can implement this by returning a function that calls the passed-in function’s bind method and return it with the arguments partially applied.

For instance, we can write the following code:

const bind = (fn, thisArg, ...partials)=> {
  return (...args) => fn.apply(thisArg, [...partials, ...args])
}

In the code above, we take the fn function, thisArg for the value of this , and partials , which is an array of arguments to be called with fn .

Then we used JavaScript’s function’s apply method to call fn with thisArg as the 1st argument to set the value of this in fn and an array of arguments, which we spread with the spread operator.

We first spread partials to apply them first, then we spread the args which we take in in the returned function.

Then when we call it as follows:

function greet(greeting, punctuation) {
  return `${greeting} ${this.user}${punctuation}`;
}

const object = {
  'user': 'joe'
};
const bound = bind(greet, object, 'hi');
console.log(bound('!'))

We see that the console log should log ‘hi joe!’ since we set the value of this in greet to object . We then applied the partial argument of 'hi' first then we called bound with the exclamation mark.

bindKey

bindKey is similar to bind except that we can use it to apply the same operations as bind to an object’s method.

It also doesn’t let us change the value of this and keep that value as the original object that the method is in.

We can implement bindKey as follows:

const bindKey = (object, key, ...partials) => {
  return (...args) => object[key].apply(object, [...partials, ...args])
}

In the code above, we take object , key , and partials as arguments. Where object is the object with the method we want to call bindKey on.

The key is the key to the method that we want to do the partial argument application on, and partials have the arguments to apply.

We can then run it as follows:

const object = {
  user: 'joe',
  greet(greeting, punctuation) {
    return `${greeting} ${this.user} ${punctuation}`;
  }
};
const bound1 = bindKey(object, 'greet', 'hi');
console.log(bound1('!'))

object.greet = function(greeting, punctuation) {
  return `${greeting} ya ${this.user} ${punctuation}`;
};

const bound2 = bindKey(object, 'greet', 'hi');
console.log(bound2('!'))

In the code above, we have our object with the greet method, which returns a string that reference this.user , which should be 'joe' .

Then we call our bindKey function with the object and the arguments we want to call the returned function with, which will be set to bound1 .

At this stage, bound1 has 'hi' set as the value of greeting . Then when we callbound1 , we passed in the '!' to it, which calls the bound1 with punctuation .

Then we get 'hi joe !’ from the console log.

After that, we changed object.greet to a different function. Now when we call bindKey as we did on the 2nd last line, we get the bound2 function, which has the 'hi' string applied to the object.greet method as the value off greeting .

Then when we call bound2 , we applied the '!' as the value of punctuation . Therefore, we get the string 'hi ya joe !’ logged in the console log output.

delay

The Lodash delay method runs a function after a given wait time in milliseconds. It also takes optional arguments that we can call our function with.

We can implement our own function with the setTimeout function as follows:

const delay = (fn, wait, ...args) => {
  setTimeout((...args) => fn(...args), wait, ...args)
}

In the code above, we just called setTimeout with a callback which calls fn as the first argument. The second argument has the wait time and the args are the arguments that’ll be passed into the callback, which is all the subsequent arguments.

The callback takes the args and then apply them the passed-in function fn .

Then when we call it as follows:

delay((text) => {
  console.log(text);
}, 1000, 'foo');

We get that 'foo' is logged by the function we passed into delay after 1 second.

Conclusion

To implement the bind and bindKey Lodash methods, we can use the JavaScript function’s apply method to change the value of this and apply the arguments to the passed-in function.

We can create our own Lodash delay method with the setTimeout function, which takes the number of milliseconds to delay the function call and the arguments to call the callback with.

Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Type Checks

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 some Lodash methods for doing type checks.

isBoolean

The Lodash isBoolean method checks whether a value is a boolean.

We can easily check if a value is a boolean with the typeof operator. For instance, we can write the following code:

const isBoolean = val => typeof val === 'boolean'

In the code above, we just used the typeof operator to check is val is a boolean.

Then we can call it as follows:

const result = isBoolean(true);

result is true since true is a boolean. Otherwise, if we run:

const result = isBoolean(1);

We get that result is false since 1 isn’t a boolean.

isArrayBuffer

The Lodash isArrayBuffer checks if an object is an instance of the ArrayBuffer constructor. We can use the constructor.name property of an object to do that check.

Therefore, we can write our own function to do the same thing as follows:

const isArrayBuffer = val => val.constructor.name === 'ArrayBuffer'

In the code above, we just used the constructor.name property to check if an object is an instance of theArrayBuffer constructor.

We can also use the instanceof operator to check if val is an instance of the ArrayBuffer as follows:

const isArrayBuffer = val => val instanceof ArrayBuffer

Then we can call it as follows:

const result = isArrayBuffer(new ArrayBuffer());

and result should be true since it’s an instance of ArrayBuffer .

isArrayLike

The isArrayLike method checks if an object is an array-like object by checking if the length property exists and has a value that’s greater than or equal to 0 or less than or equal to Number.MAX_SAFE_INTEGER .

With these criteria, we can implement our own isArrayLike function as follows:

const isArrayLike = val => typeof val.length === 'number' && val.length >= 0 && val.length <= Number.MAX_SAFE_INTEGER

In the code above, we check if val.length is a number with the typeof operator. Then we check if val.length is between 0 and Number.MAX_SAFE_INTEGER .

Then if we run our isArrayLike function as follows:

const result = isArrayLike('foo');

We get that result is true since a string has a length property that’s between 0 and Number.MAX_SAFE_INTEGER .

On the other hand, if we call isArrayLike with 1 as follows:

const result = isArrayLike(1);

Then we get that result is false since 1 doesn’t have a length property.

isElement

The Lodash isElement method checks whether an object is an HTML element. Since all HTML elements are an instance of the HTMLElement constructor, we can use the instanceof operator to check if an object is an instance of that constructor as follows:

const isElement = obj => obj instanceof HTMLElement

In the code above, we check if obj is an element by checking if it’s an instance of HTMLElement .

Then when we run it as follows:

const result = isElement(document.body);

We get that result is true since document.body is an HTML element, which means that it’s an instance of the HTMLElement constructor.

On the other hand, if we call it as follows:

const result = isElement('foo');

Then we get that result is false because it’s not an HTMLElement object.

isEmpty

Lodash’s isEmpty method checks whether an object, collection, map, and set is an empty object.

Objects are empty if they have no enumerable own properties. Array-like values like arguments , arrays, strings, etc. are considered empty is the length is 0.

Maps and sets are considered empty if their length is 0.

With the conditions clearly defined, we can write our own function to do the isEmpty check.

We can implement our own isEmpty function as follows:

const isEmpty = obj => {
  if (typeof obj.length === 'number') {
    return obj.length === 0;
  } else if (obj instanceof Map || obj instanceof Set) {
    return obj.size === 0;
  } else {
    return Object.keys(obj).length === 0;
  }
}

In the code above, we check if the length property is a number to check whether obj is an array-like object. If it is, then we return obj.length === 0 .

If obj is an instance of the Map or Set constructor, we can check the size property instead of the length property.

Otherwise, we use Object.keys with obj as the argument and get the length property and check if it’s 0.

Then if we call it as follows:

const result = isEmpty('');

We get that result is true since an empty string has length 0.

Conclusion

We can do type checking of primitive values with the typeof operator. For objects, it’s better to use the instanceof operator to get the name of the constructor as a string.

To get the size of an array-like object, we use the length property. Otherwise, we use the size property for Map and Set instances.

Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Merging 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 how to implement some Lodash object merging methods ourselves with the spread operator and plain JavaScript object operators and methods.

assign

The Lodash’s assign method assigns all of an object’s own enumerable string keyed properties of the source object to the destination object.

Source objects are applied from left to right. Plain JavaScript already has the Object.assign method in its standard library, so we can use that to implement this method.

The assign method mutates the original object to add the keys of the other objects to it.

For instance, we can do that as follows:

const assign = (obj, ...sources) => {
  for (const s of sources) {
    obj = {
      ...obj,
      ...s
    };
  }
  return obj;
}

In the code above, we have our own assign function, which takes the same arguments as Lodash’s assign method. It takes obj , which is the original object. The sources are the objects that we want to merge into obj .

Then we have a for...of loop, which loops through the sources , which is an array of object originating from the arguments that we passed in because we applied the rest operator to it.

In the loop, we applied the spread operator to obj and each object in sources to merge them into one. Then we return obj .

We can also use the plain JavaScript’s Object.assign method to do the same thing as follows:

const assign = (obj, ...sources) => {
  return Object.assign(obj, ...sources);
}

We just called Object.assign with obj as the first argument, and the sources array spread as the arguments of the assign method’s subsequent arguments.

In the end, we can call either one as follows:

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

function Bar() {
  this.c = 3;
}

Foo.prototype.b = 2;
Bar.prototype.d = 4;

console.log(assign({
  'a': 0
}, new Foo(), new Bar()));

Then we get that the console log outputs {a: 1, c: 3} since it merges in the source objects’ own enumerable properties only, which don’t include any properties in the prototype.

assignIn

The Lodash assignIn method is like the assign method, but it also merges the source object’s prototypes’ properties into the object.

Therefore, we can implement it in a similar way as the assign function, except that we need to call the Object.getPrototypeOf method to get the prototype of the objects that we have in sources so that we can merge their prototypes’ properties into our returned object.

For instance, we can implement assignIn in the following way:

const assignIn = (obj, ...sources) => {
  for (const s of sources) {
    let source = s;
    let prototype = Object.getPrototypeOf(s)
    while (prototype) {
      source = {
        ...source,
        ...prototype
      }
      prototype = Object.getPrototypeOf(prototype)
    }
    obj = {
      ...obj,
      ...source
    };
  }
  return obj;
}

In the code above, we have the same parameters and the same for...of loop as assignIn .

However, inside the loop, we have the source and prototype variables. The prototype variable is used to traverse up the object’s prototype chain to merge all its prototypes’ properties into it up the prototype chain. We did the traversal with the Object.getPrototypeOf method and the while loop.

Then we used the spread operator to merge in the source object with all its prototypes’ properties merged in into the obj object.

Now, when we call assignIn as follows:

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

function Bar() {
  this.c = 3;
}

Foo.prototype.b = 2;
Bar.prototype.d = 4;

console.log(assignIn({
  'a': 0
}, new Foo(), new Bar()));

We get {a: 1, b: 2, c: 3, d: 4} as the value logged from the console log because all of Foo and Bar instance variables have been added to the Foo and Bar instances as their own properties.

Conclusion

To implement the Lodash assign method, we just need to use the spread operator to merge the object’s own properties into the object that we want to have the properties merged in.

The assignIn method is more complex because we have to traverse up the prototype chain to merge in all those properties as well. We can do that by using a while loop with the Object.getPrototypeOf method.

Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Flattening and Mapping

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 create our own methods to flatten collections.

flatMap

The Lodash flatMap method runs an iteratee function on each array entry of the original array and then flattens the resulting array and returns it.

We can implement it as follows:

const flatMap = (arr, iteratee) => arr.map(iteratee).flat()

In the code above, we called the map method on arr to map each entry to iteratee then called flat to flatten the resulting array.

Then when we call our flatMap function as follows:

const result = flatMap([1, 2], a => [a, a]);

We get that result is [1, 1, 2, 2] .

flatMapDeep

Lodash’s flatMapDeep method is like flatMap , but recursively flattens the resulting array.

We can implement this as we did with the flatMap method as follows:

const flatMapDeep = (arr, iteratee) => arr.map(iteratee).flat(Infinity)

The only difference between our flatMapDeep and flatMap method is that we passed in Infinity to flat to recursively flatten our resulting array after mapping each entry by calling iteratee .

Then when we can it as follows:

const result = flatMapDeep([1, 2], a => [[a, a]]);

result should be [1, 1, 2, 2] .

flatMapDepth

The flatMapDepth is like flatMap but we can specify the depth of the flattening of the resulting array.

The plain JS flat method also accepts the depth of the flatten as an argument, so we can just use that again:

const flatMapDepth = (arr, iteratee, depth) => arr.map(iteratee).flat(depth)

Then when we call it as follows:

const result = flatMapDepth([1, 2], a => [
  [a, a]
], 1);

We get:

[
  [
    1,
    1
  ],
  [
    2,
    2
  ]
]

as the value of result since we specified that the depth is 1.

groupBy

The groupBy method returns an object that takes the items in an array, calls an iteratee function and add that as the key of the returned object].

Then it creates an array as the value for each key, and then push the items that are the same as the key when iteratee is called with it into the array.

We can implement that as follows:

const groupBy = (arr, iteratee) => {
  let obj = {};
  for (const a of arr) {
    if (!Array.isArray(iteratee(a))) {
      obj[iteratee(a)] = [];
    }
    obj[iteratee(a)].push(a);
  }
  return obj;
}

In the code above, we looped through the items with a for...of loop, then populate the keys by calling iteratee on an array entry and then add the key with the empty array as the value.

Then when push the items into the array of the corresponding key.

Then when we call it as follows:

const result = groupBy([6.1, 4.2, 6.3], Math.floor);

We get that result is:

{
  "4": [
    4.2
  ],
  "6": [
    6.3
  ]
}

includes

The Lodash includes method checks if an item is in the collection. It also takes a starting index to start searching for.

We can implement this with the slice and includes method as follows:

const includes = (arr, value, start) => arr.slice(start).includes(value)

In the code above, we called slice on arr to start the search from the start index. Then we call array instance’s includes method to check if the item is in the sliced array.

Then when we call it as follows:

const result = includes([6.1, 4.2, 6.3], 6.3, 1);

result should be true since 6.3 is in the part of the array that has an index bigger than or equal to 1.

invokeMap

The Lodash invokeMap method maps the values of an array and returns it according to what we pass in as the argument.

Lodash invokeMap takes a string with the function name or a function to invoke on each collection entry. It also takes an argument for arguments.

We can implement it as follows:

const invokeMap = (arr, fn, ...args) => arr.map(a => fn.apply(a, args))

In the code above, we used the rest operator to spread the args into an array. Then we called map on arr to map each entry by calling apply on fn to map the values with the specified function.

We kept it simple by only assuming that fn is a function, unlike the Lodash version.

Then when we call invokeMap as follows:

const result = invokeMap([123, 456], String.prototype.split, '')

We get that result is:

[
  [
    "1",
    "2",
    "3"
  ],
  [
    "4",
    "5",
    "6"
  ]
]

since we split the number into substrings.

Conclusion

The flatMap family methods can be implemented with the map and flat methods.

To implement the groupBy method, we just have to populate an object by calling the iteratee function on each array entry and then populating them as keys. The values will be the original values that return the same value as the key when we call iteratee on it.

We can use plain JavaScript’s includes method to implement our own Lodash’s includes .

Finally, invokeMap can be implemented by using the rest operator to spread the arguments into an array and then use apply to call the passed-in function on each entry.