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 :(
9
  • this might be too hard Commented Oct 21, 2020 at 17:28
  • You've to create your own JS parser, if you can't use the built-in parser (eval), which very often is not a safe solution. Commented Oct 21, 2020 at 17:35
  • Could you give me an example? Commented Oct 21, 2020 at 17:36
  • 1
    Object.prototype.toString.call(eval('1')) ... Commented Oct 21, 2020 at 17:37
  • uhm I think I need to create my own JS parser... Could you help me with that? Commented Oct 21, 2020 at 17:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is what I've been looking for!
I just edited my question. COuld you check my test cases? It's failing :(
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
For array, don't return typeof value. Array is an object in JavaScript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.