Skip to content

Instantly share code, notes, and snippets.

@pridees
Created June 21, 2021 09:46
Show Gist options
  • Save pridees/899f92fa9a45aed0e9ef97ee17bc514a to your computer and use it in GitHub Desktop.
Save pridees/899f92fa9a45aed0e9ef97ee17bc514a to your computer and use it in GitHub Desktop.
// let assert = require('assert').strict;
const tree = {
name: "Program Files",
type: "directory",
size: undefined,
children: [
{
name: "File2",
type: "file",
size: 400,
children: null
},
{
name: "App2",
type: "directory",
size: 1200,
children: [
{
name: "File3",
type: "file",
size: 700,
children: null
},
{
name: "File4",
type: "file",
size: 500,
children: null
}
]
},
{
name: "App3",
type: "directory",
size: 300,
children: [
{
name: "File5",
type: "file",
size: 300,
children: null
},
{
name: "config",
type: "directory",
size: 900,
children: [
{
name: "File6",
type: "file",
size: 900,
children: null
}
]
}
]
},
{
name: "App3",
type: "directory",
size: 0,
children: []
}
]
}
// REFERENCE
// Задача 1 - написать функцию fileNamesUppercase, которая принимает на вход дерево и выводит имена всех файлов заглавными буквами
// сохранив структуру вложенности, пустые папки должны быть проигнорированы
// Результат
// [ 'FILE2', [ 'FILE3', 'FILE4' ], [ 'FILE5', [ 'FILE6' ] ] ]
// const task1 = [ 'FILE2', [ 'FILE3', 'FILE4' ], [ 'FILE5', [ 'FILE6' ] ] ]
// Ответ
const fileNamesUppercase = ({ children, name }) => children
? children.map(fileNamesUppercase).filter(v => v.length)
: name.toUpperCase()
// Задача 2 - написать функцию countFiles, которая принимает на вход дерево и считает количество файлов по всей глубине вложенности
// Результат: 5
// Ответ
const countFiles = ({ children }, start = 0) => children
? children.reduce((acc, v) => countFiles(v, (v.type == "file") ? acc + 1 : acc), start)
: start
// Задача 3 - Написать функцию findFilesBySize, которая принимает на вход дерево и число-размер и выводит в плоском списке имена всех файлов больше этого числа включительно
// Входные данные: 500
// Результат: [ 'File3', 'File4', 'File6' ]
const findFilesBySize = ({ children }, size = 0, initialAcc = []) => {
return children
? children.reduce((acc, v) => findFilesBySize(
v, size, (v.type == "file" && v.size >= size) ? [...acc, v.name] : acc
), initialAcc)
: initialAcc
}
console.log(fileNamesUppercase(tree))
console.log(countFiles(tree))
console.log(findFilesBySize(tree, 500))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment