Skip to content

Instantly share code, notes, and snippets.

@brunormferreira
Last active February 19, 2021 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunormferreira/db2a20efc9486c2959f4d07042259554 to your computer and use it in GitHub Desktop.
Save brunormferreira/db2a20efc9486c2959f4d07042259554 to your computer and use it in GitHub Desktop.
This is a exercise to do with Javascript.
[
{ id: 1, likes: 13, text: 'Lets code in Reactjs for all day long!' },
{ id: 2, likes: 87, text: 'Software Developer is a good choice to your life!' },
{ id: 3, likes: 51, text: 'Make your code readability.' },
{ id: 4, likes: 32, text: 'Open Source Software is the best thing for the developers learn more and more.' },
]
// -> Remove the likes property ->
[
{ id: 1, text: 'Lets code in Reactjs for all day long!' },
{ id: 2, text: 'Software Developer is a good choice to your life!' },
{ id: 3, text: 'Make your code readability.' },
{ id: 4, text: 'Open Source Software is the best thing for the developers learn more and more.'},
]
@brunormferreira
Copy link
Author

const fields = [
  {
    type: "text",
    title: "Title",
    name: "title",
    constraints: {
      required: {
        message: "^Title is required",
        allowEmpty: false
      }
    }
  },
  {
    type: "text",
    title: "Slug",
    name: "slug",
    constraints: {
      required: {
        message: "^Slug is required",
        allowEmpty: false
      },
      format: {
        pattern: "[a-z0-9_-]+",
        flags: "i",
        message: "^Can only be a valid slug"
      }
    }
  }
];

const validationRules = fields.reduce((rules, field) => {
  return Object.assign(rules, { [field.name]: field.constraints });
}, {});

console.log(validationRules);

@brunormferreira
Copy link
Author

brunormferreira commented Feb 19, 2021

Note: if you care about not mutating data, you might consider using Object.assign({}, rules, { [field.name]: field.constraints }) or using the object spread syntax, { ...rules, [field.name]: field.constraints }. I would advise against this. Personally, I’m a firm believer in the value of immutable data, but with pragmatism. In this case, a new object will be created for each iteration which could end up using quite a lot of unnecessary memory in your app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment