Skip to content

Instantly share code, notes, and snippets.

@JDMcKinstry
Last active January 18, 2017 16:38
Show Gist options
  • Save JDMcKinstry/05fd4ba55184a065f33cf48c04f33d58 to your computer and use it in GitHub Desktop.
Save JDMcKinstry/05fd4ba55184a065f33cf48c04f33d58 to your computer and use it in GitHub Desktop.
;(function() {
/**
* AssociativeArray( { key: value } )
* AssociativeArray( key, value )
* AssociativeArray( [keys], [value] )
**/
function AssociativeArray() {
var args = Array.prototype.slice.call(arguments),
arr = [];
switch (true) {
case args.length == 1 && 'object' == typeof args[0]:
var keys = Object.keys(args[0]),
vals = Object.values(args[0]);
for (var i=0;i<keys.length;i++) if (/num|str/i.test(typeof keys[i])) arr[keys[i]] = vals[i];
arr.length = vals.length; // set array length
break;
case args.length == 2 && /^\[[^\]]*\]$/.test(JSON.stringify(args)): // 2 Strings
arr[args[0]] = args[1];
arr.length = 1; // set array length
break;
case args.length == 2 && /^\[\[[^\]]*\],\[[^\]]*\]\]$/.test(JSON.stringify(args)): // 2 Arrays
var keys = args[0],
vals = args[1];
// add blank values foreach extra key if there are more keys than values
if (keys.length > vals.length) keys.map(function(v, i) { if (i >= vals.length) vals.push(void 0); });
for (var i=0;i<keys.length;i++) if (/num|str/i.test(typeof keys[i])) arr[keys[i]] = vals[i];
// append any left over values to array
if (vals.length > keys.length) vals.map(function(v, i) { if (i >= keys.length) arr.push(v); });
arr.length = vals.length; // set array length
break;
case !!arguments.length:
arr = Array.prototype.concat.apply([], arguments);
break;
}
return arr
}
window.hasOwnProperty("AssociativeArray") || (window.AssociativeArray = AssociativeArray);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment