0.0.2 • Published 3 years ago

empathy v0.0.2

Weekly downloads
3
License
MIT
Repository
github
Last release
3 years ago

Actions Status codecov License: MIT

A typeof implementation safe for Object representations of JavaScript primitives.

WhatWhere
Discussionhttps://github.com/bigeasy/empathy/issues/1
Documentationhttps://bigeasy.github.io/empathy
Sourcehttps://github.com/bigeasy/empathy
Issueshttps://github.com/bigeasy/empathy/issues
CIhttps://travis-ci.org/bigeasy/empathy
Coverage:https://codecov.io/gh/bigeasy/empathy
License:MIT
npm install empathy

What's in a name? Empathy looks deep into the soul of a variable and really feels its actual type. I found this function on StackOverflow under Check whether variable is number or string in JavaScript and again under what is the best way to check variable type in javascript, both submitted by one Michael S. Mikowski. I started to copy and paste it into one module after another. Decided it needs a base of operations, so now it lives here.

const assert = require('assert')
const sortof = require('empathy')

assert.equal(sortof(1), 'number', 'is number')
assert.equal(sortof(new Number(1)), 'number', 'object wrapped is still number')
assert.equal(sortof(null), 'null', 'is null')
assert.equal(sortof([][0]), 'undefined', 'is undefined')
assert.equal(sortof([]), 'array', 'is array')

I find that using this function not only protects against object wrappers around primitives, it simplifies the switch statements I write using typeof.

const assert = require('assert')

function counter (value) {
    switch (typeof value) {
    case 'object': {
            if (null) {
                return 1
            }
            let sum = 0
            if (Array.isArray(value)) {
                for (const item of value) {
                    sum += counter(item)
                }
            }
            for (const name in value) {
                for (const item of value) {
                    sum += counter(value[name])
                }
            }
        }
    default:
        return 1
    }
}

assert.equal(counter({ a: 'x', b: [ 'y', 'z' ] }), 3, 'found three scalar values')
const assert = require('assert')
const sortof = require('empathy')

function counter (value) {
    switch (sortof(value)) {
    case 'array': {
            let sum = 0
            for (const item of value) {
                sum += counter(item)
            }
            return sum
        }
    case 'object': {
            let sum = 0
            for (const item in value) {
                sum += counter(value[item])
            }
            return sum
        }
    default:
        return 1
    }
}

assert.equal(counter({ a: 'x', b: [ 'y', 'z' ] }), 3, 'found three scalar values')
0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago

0.0.0

10 years ago