DEV Community

Cover image for Structs in JavaScript
JoelBonetR πŸ₯‡
JoelBonetR πŸ₯‡

Posted on β€’ Edited on

19 6 1

Structs in JavaScript

Update May 8th 2022:

If you like to use it, I've just published it as npm package.
npm i makestruct

What is a struct?

A struct is used for building data structures. These structures are used to group related data together.

There are differences on how they work behind the scenes depending on the programming language but the fun thing is that there are no structs in JavaScript.

When you want to create a custom data structure in JS you usually do a single thing. Creating an Object.

const user = {
  id: 0,
  name: '',
  country: '',
  pets: [],
}
Enter fullscreen mode Exit fullscreen mode

But is there any other way to do that?

Let's try to create a function to dynamically generate "structs" in JavaScript!

dope javascript structs

/**
 * @constructor Generates a constructor for a given data structure
 * @param {string} keys separated by a comma + whitespace. struct('id, name, age')
 * @returns {constructor} Constructor for the new struct
 */
function makeStruct(keys) {
  if (!keys) return null;
  const k = keys.split(', ');
  const count = k.length;

  /** @constructor */
  function constructor() {
    for (let i = 0; i < count; i++) this[k[i]] = arguments[i];
  }
  return constructor;
}
Enter fullscreen mode Exit fullscreen mode

How it works?

It takes a comma + whitespace separated string and generates a constructor for the structure you desired, so you can now instantiate your objects using this dynamically generated constructor.

Usage:

const user = new makeStruct("id, name, country");
const johnny = new user(1, 'John', 'UK');
console.log(johnny.name); // john
Enter fullscreen mode Exit fullscreen mode

We can also assign complex structures at our properties!

const user = new makeStruct("id, name, country, pets");
const pepe = new user(1, 'Pepe', 'ES', ['Baxter', 'Flurfrils']);

console.log(pepe.pets); // ['Baxter', 'Flurfrils']
Enter fullscreen mode Exit fullscreen mode

Or adding a struct inside the other:

/**
 * @typedef UserInfo
 * @property {string} phone
 * @property {number} age
 * @property {string} hairColor
 * @constructor
 */

/** @type {ObjectConstructor|any} */
const UserInfo = new makeStruct('phone, age, hairColor');

/** @type {UserInfo} */
const extraInfo = new UserInfo('555-777-888', 31, 'blonde');


/**
 * @typedef User
 * @property {number} id
 * @property {string} name
 * @property {string} country
 * @property {UserInfo} info
 * @constructor
 */

/** @type {ObjectConstructor|any} */
const User = new makeStruct('id, name, country, info');
/** @type {User} */
const John = new User(1, 'John', 'US', extraInfo);
Enter fullscreen mode Exit fullscreen mode

Now we can do:

John.country // 'US'
John.info.phone // '555-777-888'
Enter fullscreen mode Exit fullscreen mode

Okay okay it's creating an object at the end but JavaScript is an object-based language just like Python and others, so in truth everything is an object.

And you can't say that this isn't funny!


Do you like my content?

Buy Me A Coffee

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay