Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save evgeniyworkbel/8117cc58376ec0f61c0984b5c7b81e1e to your computer and use it in GitHub Desktop.
Save evgeniyworkbel/8117cc58376ec0f61c0984b5c7b81e1e to your computer and use it in GitHub Desktop.
Курс "JS: Деревья" (Хекслет)
export default (data, replacer = ' ', spacesCount = 1) => {
const convert = (someValue, nest) => {
const entries = Object.entries(someValue);
return entries
.map(([key, value]) => {
if (typeof value === 'object' && value !== null) {
return `${replacer.repeat(spacesCount * nest)}${key}: {\n${convert(value, nest + 1)}\n${replacer.repeat(spacesCount * nest)}}`;
}
return `${replacer.repeat(spacesCount * nest)}${key}: ${value}`;
})
.join('\n');
};
const convertedValue = (typeof data === 'object') ? `{\n${convert(data, 1)}\n}` : String(data);
return convertedValue;
};
export default (data, replacer = ' ', spacesCount = 1) => {
// Define construct schema
const constructString = (initialKey, initialValue, depthLevel) => {
if (typeof initialValue === 'object' && initialValue !== null) {
return `${replacer.repeat(spacesCount * depthLevel)}${initialKey}: {\n${convert(initialValue, depthLevel + 1)}\n${replacer.repeat(spacesCount * depthLevel)}}`;
}
return `${replacer.repeat(spacesCount * depthLevel)}${initialKey}: ${initialValue}`;
};
const convert = (someValue, depth) => Object
.entries(someValue)
.map(([key, value]) => constructString(key, value, depth))
.join('\n');
return (typeof data === 'object') ? `{\n${convert(data, 1)}\n}` : String(data);
};
import _ from 'lodash';
const stringify = (value, replacer = ' ', spacesCount = 1) => {
const iter = (currentValue, depth) => {
// альтернативный вариант: (typeof currentValue !== 'object' || currentValue === null)
if (!_.isObject(currentValue)) {
return `${currentValue}`;
}
const indentSize = depth * spacesCount;
const currentIndent = replacer.repeat(indentSize);
const bracketIndent = replacer.repeat(indentSize - spacesCount);
const lines = Object
.entries(currentValue)
.map(([key, val]) => `${currentIndent}${key}: ${iter(val, depth + 1)}`);
return [
'{',
...lines,
`${bracketIndent}}`,
].join('\n');
};
return iter(value, 1);
};
export default stringify;
JavaScript содержит метод JSON.stringify() для приведения к строке любого значения. Он работает следующим образом:
JSON.stringify('hello'); // "hello" - для строковых значений добавляются кавычки
JSON.stringify(true); // true - значение приведено к строке, но без кавычек
JSON.stringify(5); // 5
const data = { hello: 'world', is: true, nested: { count: 5 } };
JSON.stringify(data); // {"hello":"world","is":true,"nested":{"count":5}}
JSON.stringify(data, null, 2); // null, 2 - указывают на два пробела перед ключом
// ключам добавляются кавычки
// в конце каждой строчки (линии) добавляется запятая, если имеется значение ниже
// {
// "hello": "world",
// "is": true,
// "nested": {
// "count": 5
// }
// }
stringify.js
Реализуйте и экспортируйте по умолчанию функцию, похожую на JSON.stringify(), но со следующими отличиями:
ключи и строковые значения должны быть без кавычек;
строчка (линия) в строке заканчивается самим значением, без запятой.
Синтаксис:
stringify(value[, replacer[, spacesCount]])
Параметры:
value
Значение, преобразуемое в строку.
replacer, необязательный
Строка - отступ для ключа; Значение по умолчанию - один пробел.
spacesCount, необязательный
Число - количество повторов отступа ключа. Значение по умолчанию - 1.
import stringify from './stringify.js';
stringify('hello'); // hello - значение приведено к строке, но не имеет кавычек
stringify(true); // true
stringify(5); // 5
const data = { hello: 'world', is: true, nested: { count: 5 } };
stringify(data); // то же самое что stringify(data, ' ', 1);
// {
// hello: world
// is: true
// nested: {
// count: 5
// }
// }
stringify(data, '|-', 2);
// Символ, переданный вторым аргументом повторяется столько раз, сколько указано третьим аргументом.
// {
// |-|-hello: world
// |-|-is: true
// |-|-nested: {
// |-|-|-|-count: 5
// |-|-}
// }
Подсказки
чтобы лучше понять как работает JSON.stringify(), запускайте его с разными данными и параметрами в консоли браузера.
проверки в тестах идут от простого к сложному:
проверка на примитивных типах;
проверка на "плоских" данных;
проверка на "вложенных" данных.
Реализуйте функцию так же пошагово, проверяя, что изменения для сложных кейсов не сломали более простые;
используйте метод repeat() (на MDN)
документация по JSON.stringify на MDN.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment