zalofg zalofg - 1 month ago 7
Javascript Question

Javascript function to derive "smallest" data type?

How could I implement a function in javascript which would take a list of strings as input, and would output the "smallest" (loosely speaking) type that all those strings can be parsed to?


  • Input: ["true", "false", "false"] => Output: "boolean".

  • Input: ["1", "4", "-9"] => Output: "int".

  • Input: ["1", "4.3", "-9"] => Output: "float" (or "double", doesn't matter).

  • Input: ["9/1/2016", "2016-9-1"] => Output: "DateTime".

  • Input: ["1", "4.3", "9/1/2016", "Nastassja Kinski"] => Output: "string".


  • It's ok to label everything else (functions, objects, arrays) as "string".

  • It's ok to label anything date-related as "DateTime", even if there is not time component present.

  • It requires differentiation between int and float (that's why my ouputs are strings instead of native types such as Number).

  • It doesn't need to be perfect; just something that roughly works (at I can refine if needed).

  • The input arrays would have 100 elements each.

Thanks a lot!


Thinking about it declaratively, it's quite easy, if you think about the criteria:

function getType(arr) {
    if (arr.every(s => s === 'true' || s === 'false'))
        return 'boolean'
    else if (arr.every(s => isNaN(Number(s)) === false)) {
        if (arr.every(n => Number(n) % 1 === 0)) return 'int'
        else return 'float'
    else if (arr.every(s => isNaN(Date.parse(s)) === false)) 
        return 'DateTime'
    else return 'string'

Testing with your inputs:

> getType(["true", "false", "false"])
> getType(["1","4","-9"])
> getType(["1","4.3","-9"])
> getType(["9/1/2016", "2016-9-1"])
> getType(["1", "4.3", "9/1/2016", "Nastassja Kinski"])

The difficulty arises when people try to think of the code that produces the result; instead, if you think about what you want and not how to write the code, the requirements become more clear and the solution becomes more apparent.

The other thing to learn here is how we let javascript (or the language of choice if it's different) do as much work for us as possible. Use clear predicate syntax and built-in functions (isNaN and built-in Date objects), and it's only 8 lines of code and clear to understand.

Someone commented about the date format varying across implementations and this is a good point. Though common date formats are going to be supported on all major implementations, if we find that our date formats are more exotic, then we can simply write our own date validator and plug it in. Either way, the approach remains the same:

else if (arr.every(s => myCustomDateValidator(s)))
    return 'DateTime'