1

Is it possible to create an array of objects that perform a function? For example, like this:

<script>
console.clear();

const acts = [
  { 'inc' : (x) => x+1 },
  { 'dec' : (x) => x-1 } 
];

console.log(acts.inc(10));
console.log(acts.dec(15));

</script>

The above gives an error -- TypeError: acts.inc is not a function.

3 Answers 3

2

You are almost there! Create an object with "function properties" instead of an array of objects:

acts = {
  'inc' : (x) => x+1,
  'dec' : (x) => x-1
};

Then,

acts.inc(3)

will return:

4

In your original code, you'd have to use:

acts[0].inc(3)

because it's an array...

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

Comments

0

You can add a function to the array prototype.

Array.prototype.inc = <function>

1 Comment

Will work, but not quite answering the question I posed. Will use as last resort. Am trying to understand Object operations better.
0

For anyone interested, here is how I used the solution chosen along with an example output for each function created (with some options).

    <!DOCTYPE html><html lang="en"><head>
<title> Array of Object Functions </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- From: https://stackoverflow.com/questions/62824415/create-array-of-objects-with-function-actions -->
<style>
 body { font-size: 1.2em; line-height: 1.6; }
</style>
</head><body>
<pre id='demo'></pre>

<script>
console.clear();
// following used only for screen display testing purposes
var former = console.log;  // retain former actions of console.log
var demo=document.getElementById('demo');
console.log = function(...msg){
  former(...msg);  // maintains existing logging via the console. (optional)
  demo.append(msg.join(' ')+'\n');  // output needs to be specified
} 
// end of display testing (also shows on console.log display)


const acts = {
  'inc' : (x) => x+1,
  'dec' : (x) => x-1,
  'mul' : (x,y) => x*y,
  'div' : (x,y) => x/y,                      // careful with y=0 (no checks here)
  'pwr' : (x,y) => x**y,                     // x to power of y

  'deg' : (rad) => (rad * Math.PI / 360),    // degrees from radians
  'rad' : (deg) => (deg / Math.PI * 360),    // radians from degrees
  'pct' : (amt) => amt * 100,                // form percentage

  'bit' : (siz) => (acts.pwr(2,siz)-1).toString(2),    // form bit-mask
  'oct' : (dec) => dec.toString(8),                    // form octal
  'hex' : (dec) => dec.toString(16),                   // form hexidecimal

  'fmt' : (amt,size) => amt.toFixed(size),             // number .toFixed(#) string
  'cdt' : (dateInfo,locn='en-US') => dateInfo.toLocaleDateString(locn),   // format US Date object
};

console.log(acts.inc(10));                  // 11
console.log(acts.dec(15));                  // 14
console.log(acts.mul(4,5));                 // 20
console.log(acts.div(5,4));                 // 1.25
console.log(acts.pwr(2,16));                // 65536

console.log(acts.deg(360));                 // 3.14159...
console.log(acts.rad(Math.PI/2));           // 1.57079...
console.log(`${acts.pct(0.15)}%`);          // 15%
console.log(`${acts.pct(acts.div(7,8))}%`); // 87.5%

console.log('0b'+acts.bit(8));              // 0b11111111
console.log('10.0 = 0o'+acts.oct(10),'octal');   // 0o12
console.log('0x'+acts.hex(65535));          // 0xffff

console.log(acts.fmt(Math.PI,2));           // 3.14
console.log(acts.fmt(Math.PI,4));           // 3.1416
console.log(Math.PI);                       // full precision PI

console.log('m/d/yyyy   : ',acts.cdt(new Date()));            // current date (m/d/year format)  US
console.log('dd/mm/yyyy : ',acts.cdt(new Date(),'en-GB'));  // date (dd/mm/year format)  GB


// tests of binary range displays
console.log('\n ','----+'.repeat(6)+'--');
console.log('0b'+acts.bit(0));      // 0b0
console.log('0b'+acts.bit(0).padStart(8,'0'));     // 0b00000000
console.log('0b'+acts.bit(16));             // 0b1111...1111    (length = 16 bits)
console.log('0b'+acts.bit(16).padStart(32,'0'));   // 0b0111...1111
console.log('0b0'+acts.bit(31));             // 0b11111...11111  (length = 31 bits)
console.log('0b'+acts.bit(32).padStart(32,'0'));   // 0b1111...1111   ( = 32 bits)
console.log('\n ','----+'.repeat(6)+'--');
console.log(`Dad's birthday: ${acts.cdt(new Date(1925,1,1))}`);  // default US format
</script>

</body>
</html>

Additional comments are welcome.

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.