UNPKG

1.51 kBJavaScriptView Raw
1/*!
2 * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
3 */
4
5import template from 'babel-template';
6import {
7 booleanLiteral,
8 numericLiteral,
9 stringLiteral
10} from 'babel-types';
11
12const pattern = /^\s*?=>( async)?\s*/;
13
14const tpl = template(`
15 (function() {
16 var assert = require('assert');
17 assert.equal(result, ASSERTION);
18 })();
19`);
20
21/**
22 * Indicates whether the specified value defines a literal assertion
23 * @param {string} value
24 * @returns {Boolean}
25 */
26export function test(value) {
27 return pattern.test(value);
28}
29
30/**
31 * Builds a literal assertion
32 * @param {string} value
33 * @returns {ast}
34 */
35export function build(value) {
36 return tpl({
37 ASSERTION: literal(value.replace(pattern, ''))
38 });
39}
40
41/**
42 * Coerces a string into a type
43 * @param {string} l
44 * @returns {Literal}
45 */
46function literal(l) {
47 /* eslint complexity: [0] */
48 // eslint-disable-next-line prefer-const
49 let f, i;
50 switch (typeof l) {
51 case 'boolean':
52 return booleanLiteral(l);
53 case 'number':
54 return numericLiteral(l);
55 case 'string':
56 if (l === 'true') {
57 return booleanLiteral(true);
58 }
59 if (l === 'false') {
60 return booleanLiteral(false);
61 }
62 i = parseInt(l, 10);
63 if (!Number.isNaN(i)) {
64 return numericLiteral(i);
65 }
66 f = parseFloat(l);
67 if (!Number.isNaN(f)) {
68 return numericLiteral(f);
69 }
70 return stringLiteral(l);
71 default:
72 throw new Error('Unsupported literal type');
73 }
74}