Skip to content

Instantly share code, notes, and snippets.

@davidnguyen11
Last active August 20, 2019 01:04
Show Gist options
  • Save davidnguyen11/21d1c58457381fa1d1f812d2ced059a6 to your computer and use it in GitHub Desktop.
Save davidnguyen11/21d1c58457381fa1d1f812d2ced059a6 to your computer and use it in GitHub Desktop.
function isOk(input) {
if (Array.isArray(input)) return input.length > 0;
if (typeof input === 'object' && input) return Object.keys(input).length > 0;
if (typeof input === 'number') return true;
return Boolean(input);
}
const { isNone } = require('../src/is-none');
test('null | undefined are not OK', () => {
let input = null;
let result = isOk(input);
expect(result).toBe(false);
input = undefined;
result = isOk(input);
expect(result).toBe(false);
});
test('{} is not OK', () => {
const input = {};
const result = isOk(input);
expect(result).toBe(false);
});
test('{ foo: 1, bar: 2 } is OK', () => {
const input = { foo: 1, bar: 2 };
const result = isOk(input);
expect(result).toBe(true);
});
test('[] is not OK', () => {
const input = [];
const result = isOk(input);
expect(result).toBe(false);
});
test('[1, 2, 3] is OK', () => {
const input = [1, 2, 3];
const result = isOk(input);
expect(result).toBe(true);
});
test('" " is OK', () => {
const input = ' ';
const result = isOk(input);
expect(result).toBe(true);
});
test('"" is OK', () => {
const input = '';
const result = isOk(input);
expect(result).toBe(false);
});
test('"I am foo" is OK', () => {
const input = ' I am foo ';
const result = isOk(input);
expect(result).toBe(true);
});
test('-1, 0, 1 are OK', () => {
let input = 0;
let result = isOk(input);
expect(result).toBe(true);
input = 1;
result = isOk(input);
expect(result).toBe(true);
input = -1;
result = isOk(input);
expect(result).toBe(true);
});
test('"true" is OK, "false" is not OK', () => {
let input = true;
let result = isOk(input);
expect(result).toBe(true);
input = false;
result = isOk(input);
expect(result).toBe(false);
});
@duythinht
Copy link

Another version without IF =]]

function isNone(input) {
  switch (true) {
    case typeof input === 'undefined':
      return true
    case typeof input === 'object':
      return Object.keys(input).length === 0
    case typeof input === 'string':
      return input.trim() === ''
    case Array.isArray(input):
      return input.length === 0
    case (typeof input === 'number') || (typeof input === 'boolean'):
      return false
    default:
      return input === undefined || input === null
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment