1
1
mirror of https://github.com/kanaka/mal.git synced 2024-09-20 18:18:51 +03:00
mal/es6/printer.js

36 lines
1.2 KiB
JavaScript
Raw Normal View History

2015-08-02 06:29:44 +03:00
import { Sym, _list_Q, _vector_Q, _hash_map_Q, Atom } from './types';
2015-07-31 05:15:55 +03:00
export function pr_str(obj, print_readably) {
if (typeof print_readably === 'undefined') { print_readably = true; }
var _r = print_readably;
2015-08-02 06:29:44 +03:00
if (_list_Q(obj)) {
2015-07-31 05:15:55 +03:00
var ret = obj.map(function(e) { return pr_str(e,_r); });
return "(" + ret.join(' ') + ")";
2015-08-02 06:29:44 +03:00
} else if (_vector_Q(obj)) {
var ret = obj.map(function(e) { return pr_str(e,_r); });
return "[" + ret.join(' ') + "]";
} else if (_hash_map_Q(obj)) {
var ret = [];
for (let [k,v] of obj) {
ret.push(pr_str(k,_r), pr_str(v,_r));
}
return "{" + ret.join(' ') + "}";
2015-07-31 05:15:55 +03:00
} else if (typeof obj === "string") {
if (obj[0] === '\u029e') {
return ':' + obj.slice(1);
} else if (_r) {
return '"' + obj.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/\n/g, "\\n") + '"'; // string
} else {
return obj;
}
} else if (obj === null) {
return "nil";
2015-08-01 07:08:33 +03:00
} else if (obj instanceof Atom) {
2015-08-02 06:29:44 +03:00
return "(atom " + pr_str(obj.val,_r) + ")";
2015-07-31 05:15:55 +03:00
} else {
return obj.toString();
}
}