Semi usefull random Symbol stuff

Hey guys,
I’ve been playing around with some JS Symbol stuff over the Chrissy holly’s and have made up this “class” or should we call it a function that returns an object.

It does this:

  • adds entries to the object with Symbols as the keys
  • has a Symbol.iterator to allow iteration of the entries with their original name as the the “key” value and not the Symbol
  • allows multiple assignments with the same key e.g. “name”
  • has a get method to allow access entries via index (first to last).

I don’t have a use for it right now but I may later, if anyone can think of how this may be useful to them please share the use cases.

Merry Christmas,
Steve

let symObj = function(){return {
  add: function(key, val){
      let symbol = Symbol(key);
      this[symbol] = val; 
  },
  addAll: function(arr){
     for(let i of arr){
       let [k,v] = i;
       let symbol = Symbol(k)
       this[symbol] = v;
     }
  },
  regex: /\((.*)\)/,
  
  get: function(i){
    let vals = Object.getOwnPropertySymbols(this);
    let keys = vals.splice(1);
    let k = keys[i].toString();
    let j = k.match(this.regex)[1];
    let v = this[keys[i]];
    return JSON.parse(`{"${j}" : "${v}"}`)
  },
  
    * [Symbol.iterator] () { 
        let symbols = Object.getOwnPropertySymbols(this);
        for (let i = 1; i < symbols.length; i++) {
            let k = symbols[i].toString();
            let j = k.match(this.regex)[1]
            let v = this[symbols[i]];
            yield JSON.parse(`{"${j}" : "${v}"}`)
        }
    }
  };
}
let users = symObj();
users.add('name', 'Steve')
users.add('name', 'Dave')
users.get(1);
users.addAll([['name', 'Jim'],['name', 'Howard']]);

for(let i of users){
  console.log(i)
}
let one = users.get(1);
let jp = JSON.stringify(one);
console.log(jp)