Skip to content

Instantly share code, notes, and snippets.

@tlrobinson
Forked from 140bytes/LICENSE.txt
Created May 17, 2011 08:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tlrobinson/976148 to your computer and use it in GitHub Desktop.
Save tlrobinson/976148 to your computer and use it in GitHub Desktop.
a JavaScript hash-map kind of thing
M = function(
a // placeholder
) {
a = {}; // initialize buckets. each bucket is an array with even indexes for keys, odd indexes for values
// API is a single function for both get(key) and set(key, value)
return function(
k, // key (any JavaScript value)
v, // value (optional, triggers set)
b, // placeholder
i, // placeholder
u, // shortcut for undefined
) {
// get existing or new bucket by coercing key to a string and looking up in the buckets object
b = a[k] = a[k] || [];
// look for the matching key in the bucket
// if not found the index will be the next available slot
for (i = 0; i < b.length && b[i] !== k; i += 2);
// if value is not undefined
if (v !== u) {
b[i] = k; // set the key
b[i + 1] = v // set the value
}
// return the value
return b[i + 1]
}
}
// Issues:
// * undefined value not possible
// * keys named "hasOwnProperty", etc
M=function(a){a={};return function(k,v,b,i,u){b=a[k]=a[k]||[];for(i=0;i<b.length&&b[i]!==k;i+=2);if(v!==u){b[i]=k;b[i+1]=v}return b[i+1]}}
Copyright (c) 2011 Tom Robinson, http://tlrobinson.net/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "itty-bitty-hash-map",
"keywords": [ "hashmap", "map", "hash" ]
}
require("./index");
var m = M();
var testCases = [
[0,0],
[{},1],
[{},2],
["foo",3],
["bar",4],
[null,5],
[false,6],
[true,7],
[function x(){},8]
]
testCases.forEach(function(t) {
m(t[0], t[1]);
assert(m(t[0]) === t[1]);
})
testCases.forEach(function(t) {
assert(m(t[0]) === t[1]);
})
testCases.forEach(function(t) {
m(t[1], t[0]);
assert(m(t[1]) === t[0]);
})
testCases.forEach(function(t) {
assert(m(t[1]) === t[0]);
})
testCases.forEach(function(t) {
m(t[0], t[0]);
assert(m(t[0]) === t[0]);
})
testCases.forEach(function(t) {
assert(m(t[0]) === t[0]);
})
function assert(condition) {
if (!condition) throw new Error("Assertion Error");
}
@jed
Copy link

jed commented May 22, 2011

some ideas:

  • assignment doesn't count. you should take that out and reclaim 2 bytes
  • if(v!==u){b[i]=k;b[i+1]=v} is the same as v===u||(b[i]=k;b[i+1]=v), right?
  • can you use i in b instead of checking length?
  • name the function and use it as a bucket to save a closure

@tlrobinson
Copy link
Author

Is the idea to be as short as possible even if it already fits in 140 bytes and shortening it doesn't improve it, or just to fit in 140 bytes period? I'd rather keep it more readable.

Regarding the suggestions:

  • Sounds good.
  • That should work if you replace the semicolon with a comma and add a semicolon after the closing colon and before the return. v!==u&&(b[i]=k,b[i+1]=v) should work as well, which reads better. Saves 1 character.
  • Not without major changes. In the existing one "i" is incremented by two, and in the for-in loop "i" is enumerated as a string, which can't be used in arithmetic.
  • Not sure I understand. Name the inner function that's returned and use that in place of "b={}"? Looks like it would save 2 characters, but with the downside of more conflicting keys (apply, call, bind, length, etc).

@jed
Copy link

jed commented May 23, 2011

nice, these are good points.

as for the purpose, the idea is to pack as much stable functionality into 140 bytes as possible. the cumulative savings from small hacks make space to add functionality; in this case you might be able to save enough to support undefined.

by the way, i love this implementation. packs a lot of punch.

@bruno-c
Copy link

bruno-c commented May 26, 2011

really loving this one. a kind of functor collection, and so short. really fun to use this way:

var col = M();
col('a', 'aaaaaa');
col('b', 'bbbbbb');
col('c', 'cccccc');
col('d', 'dddddd');

['a', 'b', 'c', 'd'].map(col);  // ['aaaaaa', 'bbbbbb'... ]

@tlrobinson
Copy link
Author

bruno does that actually work? Doesn't map pass the index as the second argument, which would get set as the value?

@bruno-c
Copy link

bruno-c commented May 27, 2011

you're right. weird how i didn't notice it. that's how i've used my own implementation of a similar idea, but you're right, with this one it sets the content to [0, 1, 2, 3]... it's nice to be able to map over it.

@bruno-c
Copy link

bruno-c commented May 27, 2011

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