0

Background

We have much of our data formatted like

var X = {value:'some val',error:'maybe an error',valid:true}

  • as a result we find ourselves calling X.value ALL the time.
  • We don't use the .error or .valid nearly as much, but we do use it.

What I want

To quit calling .value everywhere, but to still have access to meta data on a per data point level.

The Question

Is there one of

A) A way to put meta data on a primitive? attaching .error to an int for example? Is it possible for bools or strings?

B) A way to make a class that can be treated as a primitive, providing a specific data member when I do? IE X.value = 5, X+3 returns 8.

C) A better design for our data? Did we just lay this out wrong somehow?

2 Answers 2

1

You can set the method toString() to your object and return value.

var X = {
  value: 1,
  error:'maybe an error',
  valid:true,
  
  toString: function() {
    return this.value;
  }
}

X.value = 5;
console.log(X+3);

Sign up to request clarification or add additional context in comments.

Comments

0

You can represent you data as a function object that also has properties:

var X = () => 1;
X.value = 1;
X.error = 'maybe an error';
X.valid = true,

console.log(X()); // 1
console.log(X.valid); // true

For better design you can encapsulate the creation of the data object in another function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.