AvnerCohen / inferify

Return a string representing the common datatype of a given Object[].
MIT License
0 stars 1 forks source link

Infer types for complete objects #3

Closed eladb closed 11 years ago

eladb commented 11 years ago

This could be useful as part of inferify (I think):

var inferify = require('inferify');

function infer_types(data) {
  var samples = {}; // <-- array of sample values for each attribute

  // go over 10 items (or less) and collect samples per field
  for (var i = 0; i < Math.min(data.length, 10); ++i) {
    var item = data[i];
    Object.keys(item).forEach(function(attr) {
      var value = item[attr];
      if (typeof value === 'undefined') return; // skip
      if (!samples[attr]) samples[attr] = [];
      samples[attr].push(value);
    });
  }

  // now that we have samples for each attribute, use inferify to infer
  // the data type for each of them.
  var types = {};
  Object.keys(samples).forEach(function(attr) {
    types[attr] = inferify(samples[attr]);
  });

  return types;
}

Usage:

assert.deepEqual(infer_types([
  { a: 23, b: 'hello' },
  { a: 22, b: 'goodbye' }
]), { a: 'integer', b: 'string' });
AvnerCohen commented 11 years ago

Sounds good as a utility method. Feel free to pull request it, else I'll probably get to it soon enough.

eladb commented 11 years ago

Will do

On Sat, Nov 17, 2012 at 10:23 PM, Avner Cohen notifications@github.comwrote:

Sounds good as a utility method. Feel free to pull request it, else I'll probably get to it soon enough.

— Reply to this email directly or view it on GitHubhttps://github.com/AvnerCohen/inferify/issues/3#issuecomment-10478489.

eladb commented 11 years ago

Sent PR

On Mon, Nov 19, 2012 at 1:24 PM, Elad Ben-Israel elad.benisrael@gmail.comwrote:

Will do

On Sat, Nov 17, 2012 at 10:23 PM, Avner Cohen notifications@github.comwrote:

Sounds good as a utility method. Feel free to pull request it, else I'll probably get to it soon enough.

— Reply to this email directly or view it on GitHubhttps://github.com/AvnerCohen/inferify/issues/3#issuecomment-10478489.

AvnerCohen commented 11 years ago

as per PR #4 - closed.