iterable-to-string.js 1.18 KB
Newer Older
YazhouChen's avatar
YazhouChen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
"use strict";

var slice = require("@sinonjs/commons").prototypes.string.slice;
var typeOf = require("@sinonjs/commons").typeOf;
var valueToString = require("@sinonjs/commons").valueToString;

module.exports = function iterableToString(obj) {
    var representation = "";

    function stringify(item) {
        return typeof item === "string"
            ? "'" + item + "'"
            : valueToString(item);
    }

    function mapToString(map) {
        /* eslint-disable-next-line local-rules/no-prototype-methods */
        map.forEach(function(value, key) {
            representation +=
                "[" + stringify(key) + "," + stringify(value) + "],";
        });

        representation = slice(representation, 0, -1);
        return representation;
    }

    function genericIterableToString(iterable) {
        /* eslint-disable-next-line local-rules/no-prototype-methods */
        iterable.forEach(function(value) {
            representation += stringify(value) + ",";
        });

        representation = slice(representation, 0, -1);
        return representation;
    }

    if (typeOf(obj) === "map") {
        return mapToString(obj);
    }

    return genericIterableToString(obj);
};