0

I'm trying to get the DataType(?) from string input value.

const data = ['1', 'hello', '[]', '{key: [value]}', '`2020-10-08`'];

function funct(data: string): DataType {
    if(??) {
        return Object
    } else if(??) {
        return Number
    } else if(??) {
        return Array
    } else if (??) {
        return Date
    }
    return String
}

data.map((d) => console.log(funct(data)));
// Number, String, Array, Object, Data

function funct(d) {
    if(d.startsWith('{') && d.endsWith('}')) {
        return typeof {}
    } else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
        return 'Date';
    } else if(!isNaN(parseFloat(d))) {
        return typeof 1
    } else if(d.startsWith('[') && d.endsWith(']')) {
        return typeof []
    } else return typeof 'string'
}
console.log('number', funct('1'));
console.log('number', funct('123'));
console.log('string', funct('`as2d`'));
console.log('string', funct('2s2d'));
console.log('Object', funct('{}'));
console.log('Array', funct('[]')); //object :( 
console.log('Array', funct('["d", "f"]')); //object :(
merry-go-round
  • 4,533
  • 10
  • 54
  • 102

1 Answers1

1

You can try something like this:

function funct(d) {
    
    if(d.startsWith('{') && d.endsWith('}')) {
        return Object
    } else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
        return Date;
    } else if(!isNaN(parseFloat(d))) {
        return Number
    } else if(d.startsWith('[') && d.endsWith(']')) {
        return Array
    } else return String
}

Note: this was tested in JS so, I removed the type annotations. Please them if you want to compile it in TypeScript.

Abrar Hossain
  • 2,594
  • 8
  • 29
  • 54
  • This is what I've been looking for! – merry-go-round Oct 21 '20 at 18:38
  • I just edited my question. COuld you check my test cases? It's failing :( – merry-go-round Oct 21 '20 at 18:38
  • number function Number() { [native code] } number function Number() { [native code] } string function String() { [native code] } string function Number() { [native code] } Object function Object() { [native code] } Array function Array() { [native code] } Array function Array() { [native code] } This is the output when I ran your code. Looks okay to me – Abrar Hossain Oct 21 '20 at 18:42
  • For array, don't return typeof value. Array is an object in JavaScript – Abrar Hossain Oct 21 '20 at 18:45