UNPKG

hexlet-pairs

Version:
90 lines (80 loc) 2.17 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * Check if something is pair * @example * const pair = cons(5, 'hello'); * isPair(pair); // true * isPair(5); // false **/ var isPair = exports.isPair = function isPair(pair) { return typeof pair === 'function' && pair.pair; }; var checkPair = exports.checkPair = function checkPair(pair) { if (!isPair(pair)) { var value = (typeof pair === 'undefined' ? 'undefined' : _typeof(pair)) === 'object' ? JSON.stringify(pair, null, 2) : String(pair); throw new Error('Argument must be pair, but it was \'' + value + '\''); } }; /** * Build pair * @example * const pair = cons(5, 'hello'); * @example * const pair = cons(cons(1, null), 'world'); **/ var cons = exports.cons = function cons(a, b) { var pair = function pair(message) { switch (message) { case 'car': return a; case 'cdr': return b; default: throw new Error('Unknown message \'' + message + '\''); } }; pair.pair = true; return pair; }; /** * Get car (first element) from pair * @example * const pair = cons(5, 'hello'); * car(pair); // 5 **/ var car = exports.car = function car(pair) { checkPair(pair); return pair('car'); }; /** * Get cdr (second element) from pair * @example * const pair = cons(5, 'hello'); * cdr(pair); // hello **/ var cdr = exports.cdr = function cdr(pair) { checkPair(pair); return pair('cdr'); }; /** * Convert pair to string (recursively) * @example * toString(cons('', 10)); // ('', 10) **/ var toString = exports.toString = function toString(pair) { checkPair(pair); var rec = function rec(p) { if (!isPair(p)) { return String(p); } var left = car(p); var right = cdr(p); return '(' + rec(left) + ', ' + rec(right) + ')'; }; return rec(pair); }; //# sourceMappingURL=index.js.map